在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python  網(wǎng)絡(luò)安全  HTML/ pyqt中如何從一個類中調(diào)用某個部件?

pyqt中如何從一個類中調(diào)用某個部件?

為了鞏固pyqt,我最近在寫一個比較大的應(yīng)用,會遇到在一個類中對另一個類中的部件進行操作的情況。
比如,一個類定義了gui中顯示數(shù)據(jù)的表格qtable,現(xiàn)在我要在另一個類中對這個表格進行操作,需要能夠?qū)?shù)據(jù)進行提取,修改和保存等,同時也可以對表格的大小進行修改。
那么我要怎么辦呢?目前使用數(shù)組存取表格的數(shù)據(jù)并進行操作,而對表格大小的修改是直接聲明全局變量的:
global qtable
這樣做雖然能夠?qū)崿F(xiàn),但總覺得不好,想問下大家如何實現(xiàn)。
比如這樣的代碼,怎樣避免使用global,或者有什么其他的實現(xiàn)方法嗎?

import sys
from PyQt4 import QtGui, QtCore

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent = None):
        QtGui.QMainWindow.__init__(self)
        
        load_file = QtGui.QAction("Load", self)
        load_file.triggered.connect(self.loadFile)
        save_file = QtGui.QAction("Save", self)
        save_file.triggered.connect(self.saveFile)

        menubar = self.menuBar()
        file = menubar.addMenu('&File')
        file.addAction(load_file)
        file.addAction(save_file)
        
        self.tab = Tab()
        
        self.setCentralWidget(self.tab)
    
    def loadFile(self):
        load_file = QtGui.QFileDialog.getOpenFileName(self, "Open file", "./", "All files(*)")
        if load_file:
            with open(load_file, "r") as load_data:
                data = eval(load_data.read())

            table.filling(data)
                        
    def saveFile(self):
        save_file = QtGui.QFileDialog.getSaveFileName(self, "Save file", "./", "All files(*)")
        if save_file:
            with open(save_file, "w") as save_data:
                save_data.write(repr(DATA))

class Tab(QtGui.QTabWidget):
    def __init__(self, parent=None):
        QtGui.QTabWidget.__init__(self)
        
        self.addTab(Table(), "TABS")

class Table(QtGui.QTableWidget):
    def __init__(self, parent = None):
        QtGui.QTableWidget.__init__(self)

        self.setRowCount(4)
        self.setColumnCount(2)
        self.itemChanged.connect(self.getData)
        global table
        table = self

    def getData(self):
        data = []
        for row in range(4):
            row_data = []
            for col in range(2):
                if self.item(row, col):
                    text = self.item(row, col).text()
                    row_data.append(str(text))
                else:
                    row_data.append("")
            data.append(row_data)
        global DATA
        DATA = data
    
    def filling(self, data):
        for row in range(4):
            for col in range(2):
                new_item = QtGui.QTableWidgetItem("")
                self.setItem(row, col, new_item)
                self.item(row, col).setText(data[row][col])

app = QtGui.QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())
回答
編輯回答
葬愛

應(yīng)該使用模型操作。 可以先看一下QT的 MVC架構(gòu)

2018年7月28日 21:35
編輯回答
淚染裳

用信號和槽啊,事件觸發(fā)

2017年6月1日 22:41