繁体   English   中英

QTableWidget中的PyQt5 QComboBox

[英]PyQt5 QComboBox in QTableWidget

我真的尽了一切办法解决我的问题,但是没有用。 这是我的简单代码,可将组合框放在表的每一行中。 它实际上适用于setItem(),我用于将字符串放入每行中。 但这不适用于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()

您创建了一个组合框,因此当将其放入单元格时,会将其从prevoius单元格中删除。 您必须为每个单元格创建一个组合框(在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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM