QTableWidget 中的 PyQt5 QComboBox

sai*_*tam 1 python qt qtablewidget qcombobox pyqt5

我真的已经尝试了一切来解决我的问题,但它不起作用。这是我将组合框放入表格每一行的简单代码。它实际上适用于 setItem(),我用它来将字符串放入每一行。但它不适用于 setCellWidget(),我必须使用 setCellWidget() 将组合框放入行中。就好像 setCellWdiget() 将组合框放入行后删除它,因为它最终只出现在最后一行,我不明白为什么。如果你们中有人能帮助我,那就太好了。提前谢谢了!

这是代码:

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()
Run Code Online (Sandbox Code Playgroud)

Fab*_*bio 6

您创建了一个组合框,因此当您将其放入单元格中时,它将从前一个单元格中删除。您必须为每个单元格(在循环中)创建一个组合框for

例子:

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
Run Code Online (Sandbox Code Playgroud)