使用QtDesigner PyQt4创建自定义小部件



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

我想看看如何在QTable Widgets的单元格中添加Qbutton或QCheckboxGroup,当用户在运行时点击向QTable添加新行时,就会添加这些控件。

在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将被重载,当按下时,它会向mainWindow发出信号printButtonContent,因此方法PrintButtonContent将打印rowId。你可以用这种方式重载任何你想要的小部件。

相关内容

  • 没有找到相关文章

最新更新