Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
========================
View Exercise 1 Solution
========================
main.py
#######
.. code-block:: python
from __future__ import (absolute_import,division,print_function)
import PyQt4.QtGui as QtGui
import PyQt4.QtCore as QtCore
import sys
import view
"""
A wrapper class for setting the main window
"""
class demo(QtGui.QMainWindow):
def __init__(self,parent=None):
super(demo,self).__init__(parent)
self.window = QtGui.QMainWindow()
my_view = view.view()
# set the view for the main window
self.setCentralWidget(my_view)
self.setWindowTitle("view tutorial")
def qapp():
if QtGui.QApplication.instance():
_app = QtGui.QApplication.instance()
else:
_app = QtGui.QApplication(sys.argv)
return _app
app = qapp()
window = demo()
window.show()
app.exec_()
view.py
#######
.. code-block:: python
from __future__ import (absolute_import,division,print_function)
import PyQt4.QtGui as QtGui
import PyQt4.QtCore as QtCore
class view(QtGui.QWidget):
def __init__(self, parent=None):
super(view, self).__init__(parent)
grid = QtGui.QVBoxLayout(self)
self.table = QtGui.QTableWidget(self)
self.table.setRowCount(4)
self.table.setColumnCount(2)
grid.addWidget(self.table)
self.colours = QtGui.QComboBox()
options = ["Blue", "Green", "Red"]
self.colours.addItems(options)
self.grid_lines = QtGui.QTableWidgetItem()
self.grid_lines.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
self.grid_lines.setCheckState(QtCore.Qt.Unchecked)
self.addItemToTable("Show grid lines", self.grid_lines, 1)
self.freq = QtGui.QTableWidgetItem("1.0")
self.phi = QtGui.QTableWidgetItem("0.0")
self.addWidgetToTable("Colour", self.colours, 0)
self.addItemToTable("Frequency", self.freq, 2)
self.addItemToTable("Phase", self.phi, 3)
self.plot = QtGui.QPushButton('Add', self)
self.plot.setStyleSheet("background-color:lightgrey")
grid.addWidget(self.plot)
self.setLayout(grid)
def setTableRow(self, name, row):
text = QtGui.QTableWidgetItem(name)
text.setFlags(QtCore.Qt.ItemIsEnabled)
col = 0
self.table.setItem(row, col, text)
def addWidgetToTable(self, name, widget, row):
self.setTableRow(name,row)
col = 1
self.table.setCellWidget(row, col, widget)
def addItemToTable(self, name, widget, row):
self.setTableRow(name, row)
col = 1
self.table.setItem(row, col, widget)
In the above code the following functions have been added to prevent
repetition of code:
- ``setTableRow`` sets the label for the table row
- ``addWidgetToTable`` adds a widget to the table
- ``addItemToTable`` adds an item to the table (needed because the
frequency and phase are items and not widgets)