Reputation: 8277
Can anyone please suggest me best practice to create a Custom widget using PyQt4 ?
I want to see how to approach adding Qpushbutton or QCheckboxGroup inside the cells of QTable Widgets that will be added on user clicking add new row to QTable at runtime
Upvotes: 0
Views: 852
Reputation: 3661
Create your custom widget in QtDesigner, save it as name.ui
. In cmdp go to file name.ui
location and use this command to convert it to python module :
pyuic4 -x name.ui -o name.py
later you can import that module (custom widget) and use it in your GUI. In your case you can create main window with QTableWidget and QPushButton in that way, but you can't make dynamical buttons inside table. You must re-implement QPushButton class like this:
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()
I hope this helps: When you press addRowButton
(simple QPushButton), AddRowToTable
will add row in table. In last column of the row will be overloaded QPushButton which when pressed, emits signal printButtonContent
to mainWindow so method PrintButtonContent
will print rowId. You can overload any widget you want in that way.
Upvotes: 1