单个模型连接到多个对话框上的多个视图,而不是更新

时间:2013-04-01 02:46:48

标签: python model-view-controller pyqt4

连接到同一模型的两个独立表单。据我了解模型视图如何工作,连接到模型的所有视图都应该在模型中显示数据。但这种情况并非如此。请参阅随附的代码。

class Model(QStringListModel):

    def __init__(self, parent=None):
        super(Model, self).__init__(parent)
        data = QStringList()
        data << "one" << "two" << "three" << "four" << "five"
        self.setStringList(data)


class Form_2(QDialog):

    def __init__(self, parent=None):
        super(Form_2, self).__init__(parent)
        self.model = Model()
        self.combo = QListView()
        self.combo.setModel(self.model)

        layout = QVBoxLayout()
        layout.addWidget(self.combo)
        self.setLayout(layout)


class Form_1(QDialog):

    def __init__(self, parent=None):
        super(Form_1, self).__init__(parent)
        self.model = Model()
        self.listView = QListView()
        self.listView.setModel(self.model)
        self.combo = QComboBox()
        self.combo.setModel(self.model)
        self.form2_button = QPushButton("Open Form_2")

        layout = QVBoxLayout()
        layout.addWidget(self.listView)
        layout.addWidget(self.combo)
        layout.addWidget(self.form2_button)
        self.setLayout(layout)

        self.connect(self.form2_button, SIGNAL("clicked()"), self.form_2)

    def form_2(self):
        self.ft = Form_2()
        self.ft.show()


app = QApplication(sys.argv)
form = Form_1()
form.show()
app.exec_()

1 个答案:

答案 0 :(得分:0)

感谢ccc.larc回答我的问题。你基本上需要传递你希望它使用的模型的同一个实例。

class Model(QStringListModel):

    def __init__(self, parent=None):
        super(Model, self).__init__(parent)
        data = QStringList()
        data << "one" << "two" << "three" << "four" << "five"
        self.setStringList(data)


class Form_2(QDialog):

    def __init__(self, model, parent=None):
        super(Form_2, self).__init__(parent)
        self.model = model
        self.combo = QListView()
        self.combo.setModel(self.model)

        layout = QVBoxLayout()
        layout.addWidget(self.combo)
        self.setLayout(layout)


class Form_1(QDialog):

    def __init__(self, parent=None):
        super(Form_1, self).__init__(parent)
        self.model = Model()
        self.listView = QListView()
        self.listView.setModel(self.model)
        self.combo = QComboBox()
        self.combo.setModel(self.model)
        self.form2_button = QPushButton("Open Form_2")

        layout = QVBoxLayout()
        layout.addWidget(self.listView)
        layout.addWidget(self.combo)
        layout.addWidget(self.form2_button)
        self.setLayout(layout)

        self.connect(self.form2_button, SIGNAL("clicked()"), self.form_2)

    def form_2(self):
        self.ft = Form_2(self.model)
        self.ft.show()


app = QApplication(sys.argv)
form = Form_1()
form.show()
app.exec_()