So yesterday , I worked out on the previous demonstration of different types of Window, and added some widgets to it. My objective was to learn how to take advantage of a model approach so that data comes from a single source and is not unique to its view, the advantage of this is if you update data in one widget it is reflected in other widgets instantaneously and that too without signals and slots. which means so less code and simpler approach, I will paste the code below but before i would like to show you screenshot of the three types of window holding data.
1: from PyQt4 import QtCore,QtGui
2:
3: import sys
4:
5:
6:
7: if __name__=='__main__':
8: app = QtGui.QApplication(sys.argv)
9: app.setStyle("cleanlooks")
10:
11: dialogWin=QtGui.QDialog()
12: dialogWin.setWindowTitle("QDialog Window")
13: dialogWin.setGeometry(100,230,270,210)
14: data=QtCore.QStringList()
15: data << "one" << "two" << "three" << "four" << "five"
16: layout = QtGui.QVBoxLayout(dialogWin)
17: layout.setMargin(0)
18:
19: #Create a model
20: model = QtGui.QStringListModel(data)
21: comboBox= QtGui.QComboBox()
22: # add data to combo box using model
23: comboBox.setModel(model)
24:
25: label=QtGui.QLabel("Item based widget has unique items from data")
26:
27: listWidget=QtGui.QListWidget()
28: listWidget.addItems(data)
29: count = listWidget.count()
30:
31: for i in range(count):
32: item = listWidget.item(i)
33: item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable)
34:
35:
36: layout.addWidget(comboBox)
37: layout.addWidget(label)
38: layout.addWidget(listWidget)
39:
40: ##layout.addStretch(0)
41: dialogWin.show()
42:
43: widgetWin=QtGui.QWidget()
44: widgetWin.setWindowTitle("QWidget Window")
45: widgetWin.setGeometry(400,230,270,210)
46: # add layout to widget
47: widLayout=QtGui.QVBoxLayout(widgetWin)
48: # add listView
49: listView =QtGui.QListView()
50: listView.setModel(model)
51: widLayout.addWidget(listView)
52: widgetWin.show()
53:
54: mainWindow=QtGui.QMainWindow()
55: mainWindow.setWindowTitle("QMainWindow")
56: mainWindow.setGeometry(700,230,270,210)
57:
58: mlabel=QtGui.QLabel("All of them updates at same\n time becuase all of them uses\n same model, the model\n keeps only one instance of\n the data")
59: vlabel=QtGui.QLabel("The Views interface that model and submit\n when we rename or retrieve \nwhen it shows the data.")
60: centralWidget = QtGui.QWidget()
61: vbox = QtGui.QVBoxLayout(centralWidget)
62: vbox.addWidget(mlabel)
63: vbox.addWidget(vlabel)
64: mainWindow.setCentralWidget(centralWidget)
65: mainWindow.show()
66:
67:
68: sys.exit(app.exec_())
Run the code to see the results