PyQT4: adding combobox to Qtableview

I am new to PyQT.

I'm interested in adding a combobox to each row of the tableView. Is this possible in PyQT 4?

I know this is possible in QT5 but not sure about PyQT.

Thanks in advance for your help.

+3


source to share


2 answers


Does this need to be done with a QTableView or can you do it with a QTableWidget ?

Assuming you can use Widget vs View, you can easily add a combobox (or any widget ) to the cell .


class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self,parent)
        self.table = QtGui.QTableWidget()
        self.table.setColumnCount(3)
        self.setCentralWidget(self.table)
        data1 = ['row1','row2','row3','row4']
        data2 = ['1','2.0','3.00000001','3.9999999']
        combo_box_options = ["Option 1","Option 2","Option 3"]

        self.table.setRowCount(4)

        for index in range(4):
            item1 = QtGui.QTableWidgetItem(data1[index])
            self.table.setItem(index,0,item1)
            item2 = QtGui.QTableWidgetItem(data2[index])
            self.table.setItem(index,1,item2)
            combo = QtGui.QComboBox()
            for t in combo_box_options:
                combo.addItem(t)
            self.table.setCellWidget(index,2,combo)

      


The important parts here are:



combo_box_options = ["Option 1","Option 2","Option 3"]

      

This is a list of values ​​that you want to store. In this example, there are three options.

for t in combo_box_options:
    combo.addItem(t)
self.table.setCellWidget(index,2,combo)

      

This block sets a dropdown box for each row and then adds it to the cell (the last one in this example).

The above code gives out like this:

Table Widget with Drop down

+4


source


If you really want to use QTableView

then it has a special method called setIndexWidget

and you only need the index where you want to put the widget. A small example.

    model = QStandardItemModel (4, 4)
    for row in range(4):
        for column in range(4):
            item = QStandardItem("row %d, column %d" % (row, column))
            model.setItem(row, column, item)

    self.tableView.setModel(model)
    for row in range(4):
        c = QComboBox()
        c.addItems(['cell11','cell12','cell13','cell14','cell15',])
        i = self.tableView.model().index(row,2)
        self.tableView.setIndexWidget(i,c)

      



The result is similar to the first answer.

+7


source







All Articles