sunwarr10r
sunwarr10r

Reputation: 4797

PyQt5 QComboBox in QTableWidget

I have really tried everything to solve my problem but it doesn't work. Here is my simple code to put Comboboxes in each row of the table. It actually works for setItem(), which I use to put strings into each row. But it doesn't work with setCellWidget(), which I have to use to put the Combobox into the rows. It is as if setCellWdiget() deletes the combobox after putting it into the row because it finally appears only in the very last row, which I don't get why. It would be great if somebody of you could help me out. Many thanks in advance!

Here is the code:

import sys
from PyQt5 import QtWidgets, QtCore

class Window(QtWidgets.QMainWindow):

    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50,50,500,500)
        self.setWindowTitle('PyQt Tuts')
        self.table()


    def table(self):

        comboBox = QtWidgets.QComboBox()

        self.tableWidget = QtWidgets.QTableWidget()
        self.tableWidget.setGeometry(QtCore.QRect(220, 100, 411, 392))
        self.tableWidget.setColumnCount(2)
        self.tableWidget.setRowCount(5)
        self.tableWidget.show()

        attr = ['one', 'two', 'three', 'four', 'five']
        i = 0
        for j in attr:
            self.tableWidget.setItem(i, 0, QtWidgets.QTableWidgetItem(j))
            self.tableWidget.setCellWidget(i, 1, comboBox)
            i += 1


def run():
    app = QtWidgets.QApplication(sys.argv)      
    w = Window()
    sys.exit(app.exec_())      

run()

Upvotes: 1

Views: 12511

Answers (1)

Fabio
Fabio

Reputation: 2602

You create a single combo box, so when you put it into a cell, it is removed from the prevoius cell. You must create a combo box for each cell (in the for loop).

Example:

attr = ['one', 'two', 'three', 'four', 'five']
i = 0
for j in attr:
    self.tableWidget.setItem(i, 0, QtWidgets.QTableWidgetItem(j))
    comboBox = QtWidgets.QComboBox()
    self.tableWidget.setCellWidget(i, 1, comboBox)
    i += 1

Upvotes: 7

Related Questions