Created
May 6, 2020 16:52
-
-
Save blakebjorn/d8698b6faf8c9e339737e00efb6ba1c0 to your computer and use it in GitHub Desktop.
QTableView Example
This file contains hidden or 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 | |
import random | |
from PySide2 import QtCore, QtWidgets | |
class TableModel(QtCore.QAbstractTableModel): | |
def __init__(self, parent=None, data=None, columns=None, *args): | |
QtCore.QAbstractTableModel.__init__(self, parent, *args) | |
self.dataset = data | |
self.columns = columns | |
def rowCount(self, parent) -> int: | |
return len(self.dataset) | |
def columnCount(self, parent) -> int: | |
return len(self.columns) | |
def data(self, index: QtCore.QModelIndex, role): | |
if not index.isValid(): | |
return None | |
if role == QtCore.Qt.DisplayRole: | |
return str(self.dataset[index.row()].get(self.columns[index.column()])) | |
def headerData(self, section: int, orientation: QtCore.Qt.Orientation, role: int): | |
if role == QtCore.Qt.DisplayRole and orientation == QtCore.Qt.Horizontal: | |
return self.columns[section] | |
def setData(self, index: QtCore.QModelIndex, value, role: int) -> bool: | |
return False | |
def flags(self, index: QtCore.QModelIndex) -> QtCore.Qt.ItemFlags: | |
return QtCore.Qt.ItemIsEnabled | |
if __name__ == "__main__": | |
def random_alphanumeric_string(length): | |
return "".join((random.choice( | |
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') for _ in range(length))) | |
data = [] | |
fields = ["id", "name", "value"] | |
for i in range(100000): | |
data.append({"id": i, "name": random_alphanumeric_string(6), "value": random.randint(0, 10000)}) | |
app = QtWidgets.QApplication(sys.argv) | |
data_model = TableModel(data=data, columns=fields) | |
table_view = QtWidgets.QTableView() | |
table_view.setModel(data_model) | |
table_view.show() | |
app.exec_() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment