-1

下面的代码创建了一个QComboBox. 组合的QStandardItems 是使用 data_objusingsetData方法设置的。更改combo' 的当前索引会触发run迭代combo' 的方法,并将其打印data_obj到 Python 字典中。如何让data_obj执着?

在此处输入图像描述

app = QApplication(list())


class DataObj(dict):
    def __init__(self, **kwargs):
        super(DataObj, self).__init__(**kwargs)

class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self.setLayout(QVBoxLayout())
        self.combo = QComboBox(self)

        for i in range(5):
            combo_item = QStandardItem('item_%s' % i)
            data_obj = DataObj(foo=i)
            print '..out: %s' % type(data_obj)
            combo_item.setData(data_obj, Qt.UserRole + 1)

            self.combo.model().appendRow(combo_item)

        self.combo.currentIndexChanged.connect(self.run)
        self.layout().addWidget(self.combo)

    def run(self):
        for i in range(self.combo.count()):
            item = self.combo.model().item(i, 0)
            data_obj = item.data(Qt.UserRole + 1)
            print ' ...in: %s' % type(data_obj)

if __name__ == '__main__':
    gui = Dialog()
    gui.resize(400, 100)
    gui.show()
    qApp.exec_()
4

1 回答 1

0

以下是此问题的有效解决方案:

在此处输入图像描述

app = QApplication(list())

class DataObj(dict):
    def __init__(self, **kwargs):
        super(DataObj, self).__init__(**kwargs)

class Object(object):
    def __init__(self, data_obj):
        super(Object, self).__init__()
        self.data_obj = data_obj


class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self.setLayout(QVBoxLayout())
        self.combo = QComboBox(self)

        for i in range(5):
            combo_item = QStandardItem('item_%s' % i)
            obj = Object(data_obj=DataObj(foo=i))
            print '..out: %s' % type(obj.data_obj)
            combo_item.setData(obj, Qt.UserRole + 1)

            self.combo.model().appendRow(combo_item)

        self.combo.currentIndexChanged.connect(self.run)
        self.layout().addWidget(self.combo)

    def run(self):
        for i in range(self.combo.count()):
            item = self.combo.model().item(i, 0)
            obj = item.data(Qt.UserRole + 1)
            print ' ...in: %s' % type(obj.data_obj)

if __name__ == '__main__':
    gui = Dialog()
    gui.resize(400, 100)
    gui.show()
    qApp.exec_()
于 2018-09-26T14:52:25.560 回答