Search code examples
pythonpyqt4

Adding Multiple Widgets to QTableWidget Cell in PyQt


I have a situation where i want to add 3 buttons in a QTableWidget. I could able to add a single button using below code.

self.tableWidget = QtGui.QTableWidget()

saveButtonItem = QtGui.QPushButton('Save')
self.tableWidget.setCellWidget(0,4,saveButtonItem)

enter image description here

But i want to know how to add multiple (lets say 3) buttons. I Mean Along with Save Button i want to add other 2 buttons like Edit, Delete in the same column (Actions)


Solution

  • You can simply create your own widget, containing the three buttons, e.g. via subclassing QWidget:

    class EditButtonsWidget(QtGui.QWidget):
    
        def __init__(self, parent=None):
            super(EditButtonsWidget,self).__init__(parent)
    
            # add your buttons
            layout = QtGui.QHBoxLayout()
    
            # adjust spacings to your needs
            layout.setContentsMargins(0,0,0,0)
            layout.setSpacing(0)
    
            # add your buttons
            layout.addWidget(QtGui.QPushButton('Save'))
            layout.addWidget(QtGui.QPushButton('Edit'))
            layout.addWidget(QtGui.QPushButton('Delete'))
    
            self.setLayout(layout)
    

    And then, set this widget as the cellwidget:

    self.tableWidget.setCellWidget(0,4, EditButtonsWidget())