【问题标题】:PyQt5 QComboBox in QTableWidgetQTableWidget 中的 PyQt5 QComboBox
【发布时间】:2017-02-04 19:29:51
【问题描述】:

我真的尝试了一切来解决我的问题,但它不起作用。 这是我在表格的每一行中放置组合框的简单代码。它实际上适用于 setItem(),我用它来将字符串放入每一行。但它不适用于 setCellWidget(),我必须使用它来将 Combobox 放入行中。就好像 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()

【问题讨论】:

    标签: python qt pyqt5 qtablewidget qcombobox


    【解决方案1】:

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

    【讨论】:

    • 你有一个例子来说明你的意思吗?
    • +1 根据文档:Sets the given widget to be displayed in the cell in the given row and column, passing the ownership of the widget to the table.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 2020-06-26
    • 2019-01-12
    • 2020-08-17
    相关资源
    最近更新 更多