0

谁能建议我使用 PyQt4 创建自定义小部件的最佳实践?

我想看看如何在 QTable Widgets 的单元格中添加 Qpushbutton 或 QCheckboxGroup ,这将在用户单击在运行时向 QTable 添加新行时添加

4

1 回答 1

1

在 QtDesigner 中创建您的自定义小部件,将其保存为name.ui. 在 cmdp 中转到文件name.ui位置并使用此命令将其转换为 python 模块:

pyuic4 -x name.ui -o name.py

稍后您可以导入该模块(自定义小部件)并在您的 GUI 中使用它。在您的情况下,您可以通过这种方式使用 QTableWidget 和 QPushButton 创建主窗口,但您不能在表格内创建动态按钮。您必须像这样重新实现 QPushButton 类:

import YourMainWindowModule #YourMainWindowModule is MainWindow created in QtDesigner and it has QPushButton named "addRowButton" and QTableWidget named "tableWidget", both in grid layer
import sys
from PyQt4 import QtGui, QtCore

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent = None):    
        QtGui.QWidget.__init__(self, parent)
        self.ui = YourMainWindowModule.Ui_MainWindow()
        self.ui.setupUi(self)

        self.connect(self.ui.addRowButton, QtCore.SIGNAL('clicked()'), self.AddRowToTable)
        self.connect(self, QtCore.SIGNAL("printButtonContent(PyQt_PyObject)"), self.PrintButtonContent)

    def AddRowToTable(self):
        rowData = ["some text", 65454, "more text"]# add what you want
        self.ui.tableWidget.setColumnCount(len(rowData)+1)
        row = self.ui.tableWidget.rowCount()
        self.ui.tableWidget.insertRow(row)
        for col in range(0, len(rowData)):
            item = QtGui.QTableWidgetItem(QtCore.QString(unicode(rowData[col])))
            self.ui.tableWidget.setItem(row, col, item)
        button = OverloadedPushButton(row, self)# row number is this button's ID
        button.setText("Button %s"%(row))
        self.ui.tableWidget.setCellWidget(row, len(rowData), button)

    def PrintButtonContent(self, rowId):
        print "Id of the row where clicked overloaded push button is: ", rowId
        #here you have rowId, so you know in which row button is clicked and you can do what you want

class OverloadedPushButton(QtGui.QPushButton):
    def __init__(self, rowID, mainWindow):
        super(OverloadedPushButton, self).__init__()
        self.__rowID = rowID
        self.__mainWindow = mainWindow
        self.connect(self, QtCore.SIGNAL('clicked()'), self, QtCore.SLOT("triggerOutput()")) 

    @QtCore.pyqtSlot()
    def triggerOutput(self):
        self.__mainWindow.emit(QtCore.SIGNAL("printButtonContent(PyQt_PyObject)"), self.__rowID) 

def main():
    app = QtGui.QApplication(sys.argv)
    form = MainWindow()
    form.show()
    app.exec_()

if __name__ == '__main__':
    main() 

我希望这会有所帮助:当您按下addRowButton(简单的 QPushButton)时,AddRowToTable将在表格中添加行。在该行的最后一列中将重载 QPushButton,当按下该按钮时,它会printButtonContent向 mainWindow 发出信号,因此方法PrintButtonContent将打印 rowId。您可以通过这种方式重载您想要的任何小部件。

于 2013-04-29T11:33:03.237 回答