I wanted to test PyQt to write a quick app to display and edit data in an Excel like form but the data is never shown.
Both the docs and the book I read say that using .setItem(row, colum, QTableWidgetItem(data)) on a QtableWidget object is one way to go. However, the following code doesn’t work, I only have an empty table and I can’t figure out why. Any idea ?
JavaScript
x
47
47
1
import sys
2
from PyQt5.QtWidgets import (
3
QApplication,
4
QMainWindow,
5
QTableWidget,
6
QTableWidgetItem,
7
QMenu,
8
QAction,
9
QInputDialog,
10
)
11
12
13
class SpreadsheetFramework(QMainWindow):
14
def __init__(self):
15
super().__init__()
16
self.initUI()
17
18
def initUI(self):
19
self.setMinimumSize(1000, 500)
20
self.setWindowTitle("Spreadsheet Table")
21
# Used for copy and paste actions
22
self.item_text = None
23
self.createTable()
24
self.fillTable()
25
self.show()
26
27
def createTable(self):
28
self.table_widget = QTableWidget()
29
30
self.table_widget.setRowCount(10)
31
self.table_widget.setColumnCount(10)
32
33
self.table_widget.setCurrentCell(0, 0)
34
35
self.setCentralWidget(self.table_widget)
36
37
def fillTable(self):
38
for i in range(10):
39
for j in range(10):
40
self.table_widget.setItem(i, j, QTableWidgetItem(i * j))
41
42
43
if __name__ == "__main__":
44
app = QApplication(sys.argv)
45
window = SpreadsheetFramework()
46
sys.exit(app.exec_())
47
This is what the window looks like when I run the code
Advertisement
Answer
If you want to display the data in a QTableWidgetItem and pass it through the constructor then it must be a string.
JavaScript
1
2
1
self.table_widget.setItem(i, j, QTableWidgetItem(str(i * j)))
2
The downside is that it is no longer a number but a string that represents a number.
Another better option is to use setData to pass the number to the Qt.DisplayRole role.
JavaScript
1
4
1
item = QTableWidgetItem()
2
item.setData(Qt.DisplayRole, i * j)
3
self.table_widget.setItem(i, j, item)
4