首页 > 解决方案 > PyQt5 - 从 TableWidget 上的 QcomboBox 获取信息

问题描述

我正在寻找一些代码,使我能够获取组合框的信息,我将它放在由 QtDesigner 创建的 TableView 上。

由于缺乏知识,我没有使用任何课程或代表。当我使用 TableWidget 时,该行TableWidget.cellWidget(indexofthecurrentrow, 4).currentIndex() == 0 返回了该行的当前状态,允许我更新数据库,但该行在 TableView 上不起作用,我假设是因为模型或没有委托。

相关代码如下:

for row in range(len(data_from_sqlite)):
      comboBox = QComboBox()
      comboBox.addItems('opt1', 'opt2')
      index_combo = tableview.model().index(row, 5) 
      tableview.setIndexWidget(index_combo, comboBox)

我只是不知道如何通过按钮中连接的其他功能来检索此 QComboBox 状态。我都试过了

tableview.model().index(0,4).itemData().currentIndex() #crashes

tableview.model().index(0,4).data() #returns None

提前感谢您的帮助。

标签: pythoncomboboxpyqtpyqt5qtableview

解决方案


我找到了解决我的问题的方法,正如 musicamante 所指出的,该解决方案涉及使用女巫的类,这是非常基本的,对我来说非常困难。

在 tableview 中实现组合框的循环是:

for row in range(len(data)):
    combo = combomaker(self)
    index_combo = self.tableview.model().index(row, 5)
    self.tableview.setIndexWidget(index_combo, combo)

成为组合制造商,如下所示

class combo(QComboBox):
    def __init__(self, parent):
        super().__init__(parent)
        self.addItems(['a', 'b'])
        self.currentIndexChanged.connect(self.getComboValue)

    def getComboValue(self):
        print(self.currentText())
        # return self.currentText()

我从 Jie Jenn 那里获取了代码https://www.youtube.com/watch?v=KMJTJNUzo4E

希望这对将来一些无知的程序员有所帮助。


推荐阅读