Created
June 29, 2020 19:29
-
-
Save katmai1/75aa8b03846a94fa11b38daf656c6e93 to your computer and use it in GitHub Desktop.
Example QTableView with PyQt5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
from PyQt5 import QtCore, QtGui, QtWidgets | |
from PyQt5.QtCore import Qt | |
class TableModel(QtCore.QAbstractTableModel): | |
def __init__(self, data): | |
super(TableModel, self).__init__() | |
self._data = data | |
def data(self, index, role): | |
if role == Qt.DisplayRole: | |
# See below for the nested-list data structure. | |
# .row() indexes into the outer list, | |
# .column() indexes into the sub-list | |
return self._data[index.row()][index.column()] | |
def rowCount(self, index): | |
# The length of the outer list. | |
return len(self._data) | |
def columnCount(self, index): | |
# The following takes the first sub-list, and returns | |
# the length (only works if all rows are an equal length) | |
return len(self._data[0]) | |
class MainWindow(QtWidgets.QMainWindow): | |
def __init__(self): | |
super().__init__() | |
self.table = QtWidgets.QTableView() | |
data = [ | |
[4, 9, 2], | |
[1, 0, 0], | |
[3, 5, 0], | |
[3, 3, 2], | |
[7, 8, 9], | |
] | |
self.model = TableModel(data) | |
self.table.setModel(self.model) | |
self.setCentralWidget(self.table) | |
app=QtWidgets.QApplication(sys.argv) | |
window=MainWindow() | |
window.show() | |
app.exec_() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
source: https://www.learnpyqt.com/courses/model-views/qtableview-modelviews-numpy-pandas/