Skip to content

Instantly share code, notes, and snippets.

@blakebjorn
Created May 6, 2020 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blakebjorn/d8698b6faf8c9e339737e00efb6ba1c0 to your computer and use it in GitHub Desktop.
Save blakebjorn/d8698b6faf8c9e339737e00efb6ba1c0 to your computer and use it in GitHub Desktop.
QTableView Example
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