使用setData方法时如何使数据持久化

时间:2018-09-26 04:53:22

标签: python pyside qcombobox qstandarditem

下面的代码创建一个QComboBox。组合的QStandardItem使用data_obj方法与setData一起设置。更改combo的当前索引会触发run方法,该方法会迭代combo'并显示data_obj,这会变成Python字典。如何使data_obj持久?

https://docs.microsoft.com/en-us/office/vba/api/excel.range.address#syntax

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_()

1 个答案:

答案 0 :(得分:0)

以下是该问题的可行解决方案:

enter image description here

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_()