任何人都可以請建議我使用PyQt4創建自定義小部件的最佳做法?使用QtDesigner創建自定義小部件PyQt4
我想看看如何處理添加Qpushbutton或QCheckboxGroup將在用戶點擊運行時
任何人都可以請建議我使用PyQt4創建自定義小部件的最佳做法?使用QtDesigner創建自定義小部件PyQt4
我想看看如何處理添加Qpushbutton或QCheckboxGroup將在用戶點擊運行時
添加新行QTable創建QtDesigner您的自定義窗口小部件添加的QTable的Widgets細胞內部,將其保存爲name.ui
。在中華骨髓庫去文件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。你可以以這種方式重載任何你想要的小工具。
如果這回答你的問題,請接受答案,如果你需要更多關於代碼的細節,請隨時詢問 – Aleksandar 2013-09-19 11:55:57