3

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)

Rao
  • 2,902
  • 14
  • 52
  • 70

2 Answers2

8

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())
sebastian
  • 9,526
  • 26
  • 54
5

You use a layout widget to add your widgets to, then add the layout widget to the cell.

There are a couple of different ones you can use. http://doc.qt.io/qt-4.8/layout.html

self.tableWidget = QtGui.QTableWidget()

layout = QtGui.QHBoxLayout()

saveButtonItem = QtGui.QPushButton('Save')
editButtonItem = QtGui.QPushButton('Edit')
layout.addWidget(saveButtonItem)
layout.addWidget(editButtonItem)

cellWidget = QtGui.QWidget()
cellWidget.setLayout(layout)

self.tableWidget.setCellWidget(0, 4, cellWidget)
Leon
  • 12,013
  • 5
  • 36
  • 59
  • 1
    I think you meant `self.tableWidget.setCellWidget(0,4,layout)`. – Jérôme Apr 21 '15 at 07:23
  • iam getting TypeError: QTableWidget.setCellWidget(int, int, QWidget): argument 3 has unexpected type 'QHBoxLayout' – Rao Apr 21 '15 at 08:41
  • OK, I had a read through the docs. Seems I was mistaken. I will update the answer. You need to add the layout to a QWidget first – Leon Apr 21 '15 at 09:15
  • @Leon Thx for the reply. it worked, but i need to set layout contentMargins and spacing to set the buttons perfectly. else the buttons are squezed. – Rao Apr 23 '15 at 01:43