有人可以建议我使用PyQt4创建自定义小部件的最佳做法吗?
我想看看如何在QTable Widgets的单元格中添加Qpushbutton或QCheckboxGroup,这些单元格将在用户点击在运行时向QTable添加新行时添加
答案 0 :(得分: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,当按下该键时,向mainWindow发出信号printButtonContent
,因此方法PrintButtonContent
将打印rowId。你可以用这种方式重载你想要的任何小部件。