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 ?
import sys from PyQt5.QtWidgets import ( QApplication, QMainWindow, QTableWidget, QTableWidgetItem, QMenu, QAction, QInputDialog, ) class SpreadsheetFramework(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setMinimumSize(1000, 500) self.setWindowTitle("Spreadsheet Table") # Used for copy and paste actions self.item_text = None self.createTable() self.fillTable() self.show() def createTable(self): self.table_widget = QTableWidget() self.table_widget.setRowCount(10) self.table_widget.setColumnCount(10) self.table_widget.setCurrentCell(0, 0) self.setCentralWidget(self.table_widget) def fillTable(self): for i in range(10): for j in range(10): self.table_widget.setItem(i, j, QTableWidgetItem(i * j)) if __name__ == "__main__": app = QApplication(sys.argv) window = SpreadsheetFramework() sys.exit(app.exec_())
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.
self.table_widget.setItem(i, j, QTableWidgetItem(str(i * j)))
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.
item = QTableWidgetItem() item.setData(Qt.DisplayRole, i * j) self.table_widget.setItem(i, j, item)