I’m working on a Python GUI application with PyQt5 which has a QTableView for showing data.
Here is the code:
import sys
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import Qt
class DataModel(QtCore.QAbstractTableModel):
def __init__(self):
super().__init__()
self.data = []
def data(self, index, role):
if role == Qt.DisplayRole:
return self.data[index.row()][index.column()]
def rowCount(self, index):
return len(self.data)
def columnCount(self, index):
return len(self.data[0])
class MainWindow(UI.UserInterface):
def __init__(self):
super().__init__()
self.model = DataModel()
self.load()
self.TableView.setModel(self.model)
self.TableView.resizeColumnsToContents()
self.TableView.horizontalHeader().setStretchLastSection(True)
def load(self):
try:
self.model.data = [(1, '2020-01-10 00:00:00', 'KANIA', 'HENRYK', 4219)]
except Exception:
pass
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
The class UI.UserInterface is in separate module. It has the QWidgets of the interface and layout QWidgets. One of them is QTableView.
I can't seem to find a way to set the header labels for the QTableView.
I looked for different solutions (some of them below) but none of them worked:
https://doc.qt.io/qt-5/sql-presenting.html (this one is written in C++. I don't quite understand it)
You must implement headerData():
class DataModel(QtCore.QAbstractTableModel):
# ...
def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return 'Column {}'.format(section + 1)
return super().headerData(section, orientation, role)
Obviously you can set your own labels even with a simple list containing the labels you want to show.
Note that you should be very careful with naming new attributes to subclasses as they might already exist.
Most importantly, you should not overwrite self.data.
here is an exemple using a QtableView and a set headerdata and you willbe able to modifier the data from the tableview
def exemple_table(self):
database = QSqlDatabase("QPSQL")
database.setHostName("localhost")
database.setDatabaseName("database")
database.setUserName("postgres")
database.setPassword("password")
database.open()
model_ft = QSqlTableModel(db=database)
model_ft.setTable('table')
model_ft.setHeaderData(0, Qt.Horizontal,"id")
model_ft.setHeaderData(1, Qt.Horizontal,"exemple01")
model_ft.setHeaderData(2, Qt.Horizontal,"exemple02")
model_ft.setHeaderData(3, Qt.Horizontal,"exemple03")
model_ft.setHeaderData(4, Qt.Horizontal,"exemple04")
model_ft.setHeaderData(5, Qt.Horizontal,"exemple05")
model_ft.setHeaderData(6, Qt.Horizontal,"exemple06")
model_ft.setHeaderData(7, Qt.Horizontal,"exemple07")
model_ft.removeColumns(8,1)
date = str(datetime.date.today())
self.tableView.setModel(model_ft)
self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
model_ft.setSort(0, Qt.DescendingOrder)
model_ft.select()
filter_ft = "date_d ='%s' " % (date_1)
model_ft.setFilter(filter_ft)
ps im using postgresql you can find other drivers here https://doc.qt.io/qt-5/sql-driver.html
and the filtre you can use all the SQL function
Override headerData method of QTableAbstractModel to set Columns and Rows name
def headerData(self, section: int, orientation: PySide6.QtCore.Qt.Orientation, role: int = ...):
#for setting columns name
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return f"Column {section + 1}"
#for setting rows name
if orientation == Qt.Vertical and role == Qt.DisplayRole:
return f"Row {section + 1}"
Working code:
import sys
import requests
import PySide6
from PySide6.QtWidgets import QTableView, QWidget, QApplication, QGridLayout, QHeaderView
from PySide6.QtCore import Qt, QAbstractTableModel
from PySide6.QtGui import QColor, QIcon, QPixmap
from datetime import datetime
class MagicIcon():
def __init__(self, link):
self.link = link
self.icon = QIcon()
try:
response = requests.get(self.link)
pixmap = QPixmap()
pixmap.loadFromData(response.content)
self.icon = QIcon(pixmap)
except:
pass
class TableModel(QAbstractTableModel):
def headerData(self, section: int, orientation: PySide6.QtCore.Qt.Orientation, role: int = ...):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
# return f"Column {section + 1}"
return self.columns[section]
if orientation == Qt.Vertical and role == Qt.DisplayRole:
return f"{section + 1}"
def __init__(self, _data):
self.columns = ["Account", "Investment", "KYC", "Investment Date"]
# super().__init__(self)
super(TableModel, self).__init__()
self._data = _data
self.calendarLink = "https://img.icons8.com/fluency/48/000000/windows-calendar.png"
self.dollarLink = "https://img.icons8.com/external-vitaliy-gorbachev-lineal-color-vitaly-gorbachev/40/000000/external-dollar-currency-vitaliy-gorbachev-lineal-color-vitaly-gorbachev-1.png"
self.analysis = "https://img.icons8.com/external-flatarticons-blue-flatarticons/65/000000/external-analysis-digital-marketing-flatarticons-blue-flatarticons-1.png"
self.bug = "https://img.icons8.com/offices/30/000000/bug.png"
self.account = "https://img.icons8.com/plumpy/24/000000/edit-administrator.png"
self.approvedLink = "https://img.icons8.com/external-bearicons-flat-bearicons/40/000000/external-approved-approved-and-rejected-bearicons-flat-bearicons-9.png"
self.rejectedLink = "https://img.icons8.com/external-bearicons-flat-bearicons/40/000000/external-rejected-approved-and-rejected-bearicons-flat-bearicons-11.png"
self.naLink = "https://img.icons8.com/color/48/000000/not-applicable.png"
self.calendarIcon = MagicIcon(self.calendarLink).icon
self.accountIcon = MagicIcon(self.account).icon
self.dollarIcon = MagicIcon(self.dollarLink).icon
self.approvedIcon = MagicIcon(self.approvedLink).icon
self.rejectedIcon = MagicIcon(self.rejectedLink).icon
self.naIcon = MagicIcon(self.naLink).icon
def data(self, index, role):
if role == Qt.DisplayRole:
value = self._data[index.row()][index.column()]
if isinstance(value, datetime):
return value.strftime("%Y-%m-%d")
if isinstance(value, float):
return f"{value:.2f}"
return value
if role == Qt.TextAlignmentRole:
return Qt.AlignHCenter + Qt.AlignVCenter
if role == Qt.BackgroundRole:
return QColor("#adcdff") if index.row() % 2 == 0 else QColor("#d8ffc2")
if role == Qt.DecorationRole:
value = self._data[index.row()][index.column()]
if value is None:
return self.naIcon
if isinstance(value, datetime):
return self.calendarIcon
if index.column() == 0:
return self.accountIcon
if index.column() == 1:
return self.dollarIcon
if index.column() == 2:
if value == True:
return self.approvedIcon
elif value == False:
return self.rejectedIcon
return self.naIcon
def rowCount(self, index):
return len(self._data)
def columnCount(self, index):
return len(self._data[0])
class MainWindow(QWidget):
def __init__(self):
# super().__init__()
super(MainWindow, self).__init__()
self.resizeEvent = self.onResize
self.table = QTableView()
self.setWindowIcon(MagicIcon(
"https://img.icons8.com/external-flatarticons-blue-flatarticons/65/000000/external-analysis-digital-marketing-flatarticons-blue-flatarticons-1.png"
).icon)
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
# self.table.setSizeAdjustPolicy(QHeaderView.AdjustIgnored)
# self.table.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)
data = [
["Andrew Mike", 15.255, True, datetime(2022, 1, 5)],
["Eliza Petterson", 353.555, False, datetime(2020, 1, 5)],
["Joseph Samuel", 123, None, datetime(2020, 1, 15)],
["Nita Singh", 266, True, datetime(2022, 2, 7)],
["Rahul Chakrabarti", 102, True, datetime(2019, 10, 15)],
]
self.model = TableModel(data)
self.table.setModel(self.model)
self.header = self.table.horizontalHeader()
# self.header.setSectionResizeMode(0, QHeaderView.Stretch)
# self.header.setSectionResizeMode(1, QHeaderView.)
# self.header.setSectionResizeMode(2, QHeaderView.ResizeToContents)
self.layout = QGridLayout()
self.layout.addWidget(self.table, 0, 0)
self.setLayout(self.layout)
def onResize(self, event):
# print('old', event.oldSize(), 'new', event.size())
# super(MainWindow, self).resizeEvent(event)
pass
if __name__ == "__main__":
app = QApplication(sys.argv)
wid = MainWindow()
wid.show()
sys.exit(app.exec())
Related
It is not possible to make the text crossed out in a separate cell. It turns out only to apply to everyone. Tried changing in model methods. Also applies to everyone. I looked for an example on the Internet, but it didn't work. The bottom line is for the user to select a cell, click on the button and the text in the cell becomes checked out.
My code
import sys
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
STRIKE_ROLE = Qt.UserRole + 1
import pandas as pd
class StrikeDelegate(QStyledItemDelegate):
def initStyleOption(self, option, index):
super().initStyleOption(option, index)
font = QFont(option.font)
font.setStrikeOut(index.data(STRIKE_ROLE))
option.font = font
class MyDelegate(QItemDelegate):
def setEditorData(self, editor, index):
text = index.data(Qt.EditRole) or index.data(Qt.DisplayRole)
editor.setText(text)
# def initStyleOption(self,option,index):
#
# QtWidgets.QStyledItemDelegate.initStyleOption(option,index)
# option.font().setStrikeOut(True)
class TableModel(QAbstractTableModel):
def __init__(self, data):
super(TableModel, self).__init__()
self._data = data
def setData(self, index, value, role):
self._data.iloc[index.row(), index.column()] = value
self.dataChanged.emit(index, index)
return True
def flags(self, index):
return Qt.ItemIsEnabled | Qt.ItemIsEditable |Qt.ItemIsSelectable | Qt.ItemIsDragEnabled | Qt.ItemIsDropEnabled
def data(self, index, role):
if role == Qt.DisplayRole:
value = self._data.iloc[index.row(), index.column()]
return str(value)
def rename_column(self, index, new_name):
self._data.rename(index={self._data.index[index]: new_name}, inplace=True)
return True
def rowCount(self, index):
return self._data.shape[0]
def columnCount(self, index):
return self._data.shape[1]
def headerData(self, section, orientation, role):
# section is the index of the column/row.
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
return str(self._data.columns[section])
if orientation == Qt.Vertical:
return str(self._data.index[section])
def add_empty_row(self):
self.beginResetModel()
try:
self._data = self._data.append(
pd.DataFrame(columns=self._data.columns, data=([[0] * len(self._data.columns)]),
index=['Пусто']))
except IndexError:
self._data = self._data.append(
pd.DataFrame(columns=self._data.columns, data=([[None] * len(self._data.columns)]),
index=[0]))
self.layoutChanged.emit()
self.endResetModel()
# self.inp_.add_delete_row.emit(self.createIndex(self._data.index[-1], 0), 'add_empty_row')
def delete_row(self, index):
self._data.drop(self._data.index[index.row()], inplace=True)
# self._data.reset_index(inplace=True, drop=True)
self.layoutChanged.emit()
class TaskModel(TableModel):
def add_empty_row(self):
self.beginResetModel()
try:
self._data = self._data.append(
pd.DataFrame(columns=self._data.columns, data=([['Новая задача'] * len(self._data.columns)]),
index=[self._data.index[-1] + 1]))
except IndexError:
self._data = self._data.append(
pd.DataFrame(columns=self._data.columns, data=([[None] * len(self._data.columns)]),
index=[0]))
self.layoutChanged.emit()
self.endResetModel()
def data(self, index, role):
value = self._data.iloc[index.row(), index.column()]
if role == Qt.DisplayRole:
return str(value)
if role == STRIKE_ROLE:
font=QFont('Calibri',13)
return font
def setData(self, index, value, role):
self._data.iloc[index.row(), index.column()] = value
self.dataChanged.emit(index, index)
return True
class Ui_Form(object):
def setupUi(self, Form):
if not Form.objectName():
Form.setObjectName(u"Form")
Form.resize(586, 683)
self.Form=Form
self.horizontalLayout_2 = QHBoxLayout(Form)
self.horizontalLayout_2.setObjectName(u"horizontalLayout_2")
self.dock_task_calendar = QDockWidget(Form)
self.dock_task_calendar.setObjectName(u"dock_task_calendar")
self.dock_task_calendar.setFeatures(QDockWidget.DockWidgetClosable|QDockWidget.DockWidgetMovable)
self.dockWidgetContents_task = QWidget()
self.dockWidgetContents_task.setObjectName(u"dockWidgetContents_task")
self.verticalLayout_3 = QVBoxLayout(self.dockWidgetContents_task)
self.verticalLayout_3.setObjectName(u"verticalLayout_3")
self.scrollArea_task = QScrollArea(self.dockWidgetContents_task)
self.scrollArea_task.setObjectName(u"scrollArea_task")
self.scrollArea_task.setWidgetResizable(True)
self.scrollAreaWidgetContents_task_2 = QWidget()
self.scrollAreaWidgetContents_task_2.setObjectName(u"scrollAreaWidgetContents_task_2")
self.scrollAreaWidgetContents_task_2.setGeometry(QRect(0, 0, 548, 623))
self.horizontalLayout = QHBoxLayout(self.scrollAreaWidgetContents_task_2)
self.horizontalLayout.setObjectName(u"horizontalLayout")
self.gridLayout = QGridLayout()
self.gridLayout.setObjectName(u"gridLayout")
self.verticalLayout_2 = QVBoxLayout()
self.verticalLayout_2.setObjectName(u"verticalLayout_2")
self.gridLayout.addLayout(self.verticalLayout_2, 4, 0, 1, 1)
self.tasklistView = QListView(self.scrollAreaWidgetContents_task_2)
self.tasklistView.setObjectName(u"tasklistView")
self.tasklistView.setDragEnabled(True)
self.tasklistView.setDragDropOverwriteMode(True)
self.tasklistView.setWordWrap(True)
self.tasklistView.setItemAlignment(Qt.AlignLeading)
self.gridLayout.addWidget(self.tasklistView, 4, 1, 1, 1)
self.model=TaskModel(pd.DataFrame([],columns=['a']))
self.delegater=MyDelegate()
self.tasklistView.setModel(self.model)
self.tasklistView.setItemDelegate(self.delegater)
self.label_task = QLabel(self.scrollAreaWidgetContents_task_2)
self.label_task.setObjectName(u"label_task")
sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label_task.sizePolicy().hasHeightForWidth())
self.label_task.setSizePolicy(sizePolicy)
self.label_task.setMaximumSize(QSize(16777215, 20))
self.label_task.setAlignment(Qt.AlignCenter)
self.gridLayout.addWidget(self.label_task, 2, 1, 1, 1)
self.calendar = QCalendarWidget(self.scrollAreaWidgetContents_task_2)
self.calendar.setObjectName(u"calendar")
sizePolicy1 = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
sizePolicy1.setHorizontalStretch(0)
sizePolicy1.setVerticalStretch(0)
sizePolicy1.setHeightForWidth(self.calendar.sizePolicy().hasHeightForWidth())
self.calendar.setSizePolicy(sizePolicy1)
self.calendar.setMaximumSize(QSize(16777215, 400))
self.gridLayout.addWidget(self.calendar, 1, 1, 1, 1)
self.verticalLayout = QVBoxLayout()
self.verticalLayout.setObjectName(u"verticalLayout")
self.add_task = QPushButton(self.scrollAreaWidgetContents_task_2)
self.add_task.setObjectName(u"add_task")
sizePolicy2 = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
sizePolicy2.setHorizontalStretch(0)
sizePolicy2.setVerticalStretch(0)
sizePolicy2.setHeightForWidth(self.add_task.sizePolicy().hasHeightForWidth())
self.add_task.setSizePolicy(sizePolicy2)
self.add_task.setMaximumSize(QSize(40, 40))
self.verticalLayout.addWidget(self.add_task)
self.del_task = QPushButton(self.scrollAreaWidgetContents_task_2)
self.del_task.setObjectName(u"del_task")
self.del_task.setMaximumSize(QSize(40, 40))
self.verticalLayout.addWidget(self.del_task)
self.check_task = QPushButton(self.scrollAreaWidgetContents_task_2)
self.check_task.setObjectName(u"check_task")
self.check_task.setMaximumSize(QSize(40, 40))
self.verticalLayout.addWidget(self.check_task)
self.verticalSpacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
self.verticalLayout.addItem(self.verticalSpacer)
self.gridLayout.addLayout(self.verticalLayout, 4, 2, 1, 1)
self.horizontalLayout.addLayout(self.gridLayout)
self.scrollArea_task.setWidget(self.scrollAreaWidgetContents_task_2)
self.verticalLayout_3.addWidget(self.scrollArea_task)
self.dock_task_calendar.setWidget(self.dockWidgetContents_task)
self.horizontalLayout_2.addWidget(self.dock_task_calendar)
self.add_task.pressed.connect(self.model.add_empty_row)
self.retranslateUi(Form)
self.Form.show()
# setupUi
def retranslateUi(self, Form):
Form.setWindowTitle(QCoreApplication.translate("Form", u"Form", None))
self.dock_task_calendar.setWindowTitle("")
self.label_task.setText(QCoreApplication.translate("Form", u"C\u043f\u0438\u0441\u043e\u043a \u0434\u0435\u043b/\u0437\u0430\u0434\u0430\u0447", None))
self.add_task.setText(QCoreApplication.translate("Form", u"PushButton", None))
self.del_task.setText(QCoreApplication.translate("Form", u"PushButton", None))
self.check_task.setText(QCoreApplication.translate("Form", u"PushButton", None))
# retranslateUi
if __name__ == '__main__':
app = QApplication(sys.argv)
translator = QTranslator()
if len(sys.argv) > 1:
locale = sys.argv[1]
else:
locale = QLocale.system().name()
translator.load('qt_%s' % locale,
QLibraryInfo.location(QLibraryInfo.TranslationsPath))
app.installTranslator(translator)
form=Ui_Form()
form.setupUi(QWidget())
app.exec_()
Since the OP has not provided an MRE then my solution will only limit the general logic which is:
Create a new role for each item where a boolean (or any other variable) is stored if the strike is applied.
Use a delegate to set the strike in the font.
With the clicked signal change the value stored in the role strike for selected rows.
from functools import cached_property
from PyQt5 import QtCore, QtGui, QtWidgets
STRIKE_ROLE = QtCore.Qt.UserRole + 1
class StrikeDelegate(QtWidgets.QStyledItemDelegate):
def initStyleOption(self, option, index):
super().initStyleOption(option, index)
font = QtGui.QFont(option.font)
font.setStrikeOut(index.data(STRIKE_ROLE))
option.font = font
def createEditor(self, parent, option, index):
editor = super().createEditor(parent, option, index)
font = QtGui.QFont(editor.font())
font.setStrikeOut(index.data(STRIKE_ROLE))
editor.setFont(font)
return editor
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
hlay = QtWidgets.QHBoxLayout(central_widget)
vlay = QtWidgets.QVBoxLayout()
vlay.addWidget(self.add_button)
vlay.addWidget(self.remove_button)
vlay.addWidget(self.strike_button)
vlay.addStretch()
hlay.addWidget(self.view)
hlay.addLayout(vlay)
self.add_button.clicked.connect(self.add)
self.remove_button.clicked.connect(self.remove)
self.strike_button.clicked.connect(self.strike)
#cached_property
def model(self):
return QtGui.QStandardItemModel()
#cached_property
def view(self):
view = QtWidgets.QListView()
delegate = StrikeDelegate()
view.setItemDelegate(delegate)
view.setModel(self.model)
return view
#cached_property
def add_button(self):
return QtWidgets.QPushButton("Add")
#cached_property
def remove_button(self):
return QtWidgets.QPushButton("Remove")
#cached_property
def strike_button(self):
return QtWidgets.QPushButton("Strike")
def add(self):
text, ok = QtWidgets.QInputDialog.getText(self, "Title", "Text:")
if not ok:
return
item = QtGui.QStandardItem(text)
item.setData(True, STRIKE_ROLE)
self.model.appendRow(item)
def remove(self):
rows = [index.row() for index in self.view.selectedIndexes()]
for row in sorted(rows, reverse=True):
self.model.takeRow(row)
def strike(self):
for index in self.view.selectedIndexes():
strike = self.model.data(index, STRIKE_ROLE)
self.model.setData(index, not strike, STRIKE_ROLE)
def main():
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
I'm trying to color int and float numbers in QTableView based on some rule.
I have following custom table model which works ok for pandas dataframe data source:
from PyQt5 import QtCore, QtGui
class PandasTableModel(QtGui.QStandardItemModel):
def __init__(self, data, parent=None):
QtGui.QStandardItemModel.__init__(self, parent)
self._data = data
for row in data.values.tolist():
data_row = [ QtGui.QStandardItem("{}".format(x)) for x in row ]
self.appendRow(data_row)
return
def rowCount(self, parent=None):
return len(self._data.values)
def columnCount(self, parent=None):
return self._data.columns.size
def headerData(self, x, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self._data.columns[x]
if orientation == QtCore.Qt.Vertical and role == QtCore.Qt.DisplayRole:
return self._data.index[x]
return None
but when I add function for coloring:
def data(self, index, role):
if role == Qt.ForegroundRole:
value = self._data.iloc[index.row()][index.column()]
if (
(isinstance(value, int) or isinstance(value, float))
and value < 0
):
return QtGui.QColor('red')
inside my PandasTableModel class, program still loads without errors only all cells are white and seem empty but filters on headers are still showing all unique values which means that data is loaded.
EDIT
Here is reproducible copy-paste example.
from PyQt5 import QtGui, QtWidgets
from PyQt5.QtCore import Qt
import sys
import pandas as pd
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, *args, obj=None, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.centralwidget = QtWidgets.QWidget(self)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Fixed)
self.centralwidget.setSizePolicy(sizePolicy)
self.pdtable = QtWidgets.QTableView(self.centralwidget)
dataPD = [['tom', 10, 180.3], ['nick', 15, 175.7], ['juli', 14, 160.6]]
df = pd.DataFrame(dataPD, columns=['Name', 'Age', 'Height'])
self.model = PandasTableModel(df)
self.pdtable.setModel(self.model)
self.setCentralWidget(self.centralwidget)
class PandasTableModel(QtGui.QStandardItemModel):
def __init__(self, data, parent=None):
QtGui.QStandardItemModel.__init__(self, parent)
self._data = data
for row in data.values.tolist():
data_row = [ QtGui.QStandardItem("{}".format(x)) for x in row ]
self.appendRow(data_row)
return
def rowCount(self, parent=None):
return len(self._data.values)
def columnCount(self, parent=None):
return self._data.columns.size
def headerData(self, x, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self._data.columns[x]
if orientation == Qt.Vertical and role == Qt.DisplayRole:
return self._data.index[x]
return None
def data(self, index, role):
if role == Qt.ForegroundRole:
value = self._data.iloc[index.row()][index.column()]
if isinstance(value, (int, float)) and value < 0:
return QtGui.QColor("red")
else:
QtGui.QStandardItemModel.data(self, index, role)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
app.setStyle("Fusion")
main = MainWindow()
main.show()
main.resize(600, 400)
sys.exit(app.exec_())
If you comment out whole def data(self, index, role) function you can see original dataframe in Gui App.
Here is working solution:
from PyQt5 import QtGui, QtWidgets
from PyQt5.QtCore import Qt
import sys
import pandas as pd
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, *args, obj=None, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.centralwidget = QtWidgets.QWidget(self)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Fixed)
self.centralwidget.setSizePolicy(sizePolicy)
self.pdtable = QtWidgets.QTableView(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Fixed)
self.pdtable.setSizePolicy(sizePolicy)
dataPD = [['tom', 10.0, 180.3], ['nick', 15.0, 175.7], ['juli', 14.0, 160.6]]
df = pd.DataFrame(dataPD, columns=['Name', 'Age', 'Height'])
print(df.dtypes)
self.model = PandasTableModel(df)
self.pdtable.setModel(self.model)
self.setCentralWidget(self.centralwidget)
class PandasTableModel(QtGui.QStandardItemModel):
def __init__(self, data, parent=None):
QtGui.QStandardItemModel.__init__(self, parent)
self._data = data
for row in data.values.tolist():
data_row = [ QtGui.QStandardItem("{}".format(x)) for x in row ]
self.appendRow(data_row)
return
def rowCount(self, parent=None):
return len(self._data.values)
def columnCount(self, parent=None):
return self._data.columns.size
def headerData(self, x, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self._data.columns[x]
if orientation == Qt.Vertical and role == Qt.DisplayRole:
return self._data.index[x]
return None
def data(self, index, role):
if role == Qt.ForegroundRole:
value = self._data.iloc[index.row()][index.column()]
if isinstance(value, (int, float)) and value > 0:
return QtGui.QColor("red")
elif role == Qt.DisplayRole:
return str(self._data.iloc[index.row(), index.column()])
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
app.setStyle("Fusion")
main = MainWindow()
main.show()
main.resize(600, 400)
sys.exit(app.exec_())
I'm trying to update a table/table model after loading a new csv so it shows the new values. Would updating the widget also some how manage this? I've cut down the code quite a bit below. You can use any 2 column csv:
0, 0, 0, 0, 0, 0,
import pandas as pd
from PySide2 import QtWidgets, QtGui, QtCore
def read_data(fname):
df = pd.read_csv(fname, sep=',', usecols=(0, 1), header=None)
df = df.dropna(how='any')
df = df[pd.to_numeric(df[0], errors='coerce').notnull()]
data_arr = df.to_numpy(dtype='float64')
return data_arr
class CustomTableModel(QtCore.QAbstractTableModel):
def __init__(self, data=None):
QtCore.QAbstractTableModel.__init__(self)
self.load_data(data)
def load_data(self, data):
self.input_x = data[:, 0]
self.input_y = data[:, 1]
self.column_count = 2
self.row_count = len(self.input_x)
def rowCount(self, parent=QtCore.QModelIndex()):
return self.row_count
def columnCount(self, parent=QtCore.QModelIndex()):
return self.column_count
def headerData(self, section, orientation, role):
if role != QtCore.Qt.DisplayRole:
return None
if orientation == QtCore.Qt.Horizontal:
return ("x", "y")[section]
else:
return "{}".format(section)
def data(self, index, role=QtCore.Qt.DisplayRole):
column = index.column()
row = index.row()
if role == QtCore.Qt.DisplayRole:
if column == 0:
return str(self.input_x[row])
elif column == 1:
return str(self.input_y[row])
elif role == QtCore.Qt.BackgroundRole:
return QtGui.QColor(QtCore.Qt.white)
elif role == QtCore.Qt.TextAlignmentRole:
return QtCore.Qt.AlignRight
return None
class Widget(QtWidgets.QWidget):
def __init__(self):
QtWidgets.QWidget.__init__(self)
try:
self.data
except AttributeError:
self.open_csv()
self.model = CustomTableModel(self.data)
self.table_view = QtWidgets.QTableView()
self.table_view.setModel(self.model)
resize = QtWidgets.QHeaderView.ResizeToContents
self.horizontal_header = self.table_view.horizontalHeader()
self.vertical_header = self.table_view.verticalHeader()
self.horizontal_header.setSectionResizeMode(resize)
self.vertical_header.setSectionResizeMode(resize)
self.horizontal_header.setStretchLastSection(False)
# Creating layout
self.main_layout = QtWidgets.QVBoxLayout()
self.file_button = QtWidgets.QPushButton('CSV Import', self)
self.file_button.clicked.connect(self.open_csv)
self.main_layout.addWidget(self.table_view)
self.main_layout.addWidget(self.file_button)
self.setLayout(self.main_layout)
def open_csv(self):
filename, *_ = QtWidgets.QFileDialog.getOpenFileName(self, self.tr('Open CSV'),
self.tr("~/Desktop/"), self.tr('Files (*.csv)'))
self.data = read_data(filename)
return None
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, widget):
QtWidgets.QMainWindow.__init__(self)
self.setWindowTitle('Linear Plotter')
self.setCentralWidget(widget)
self.menu = self.menuBar()
self.file_menu = self.menu.addMenu('File')
exit_action = QtWidgets.QAction('Exit', self)
exit_action.setShortcut(QtGui.QKeySequence.Quit)
exit_action.triggered.connect(self.close)
self.file_menu.addAction(exit_action)
self.status = self.statusBar()
self.status.showMessage('Data loaded and plotted')
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
widget = Widget()
window = MainWindow(widget)
window.show()
sys.exit(app.exec_())
Not sure if QWidget.update() would work? I could not get it working.
I wish to add a checkbox to a cell with text in my QTableView:
when a cell is not activated we should see a text and a greyed out checkbox, like this
when we open a delegate editor, we should be able to edit text and to change state of a checkbox
Just for info - further I was planning to do next: when a checkbox is activated - a cell will reject signal for updating text in it, and if checkbox is unchecked - text will be updated when special signal is emitted.
I understand that I should subclass QStyledItemDelegate and re-implement paint method, but as far as I am a beginner I found it difficult to figure out this task.
You can use this example to write and test a code:
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
import pickle
class Mainwindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.table = QtWidgets.QTableView()
self.setCentralWidget(self.table)
self.list = ['item_1', 'item_2','item_3']
self.data = [
[1, 'Blocks γ=500 GOST 31359-2007', self.list[0], 0.18, 0.22],
[2, 'Blocks γ=600 GOST 31359-2008', self.list[0], 0.25, 0.27],
[3, 'Insulation', self.list[0], 0.041, 0.042],
[3, 'Insulation', self.list[0], 0.041, 0.042]
]
self.model = Materials(self.data)
self.table.setModel(self.model)
self.table.setSelectionBehavior(self.table.SelectRows)
self.table.setSelectionMode(self.table.SingleSelection)
for row in range(len(self.model.materials)):
index = self.table.model().index(row,2)
self.table.setIndexWidget(index, self.setting_combobox(index))
def setting_combobox(self, index):
widget = QtWidgets.QComboBox()
list = self.list
widget.addItems(list)
widget.setCurrentIndex(0)
widget.currentTextChanged.connect(lambda value: self.model.setData(index, value))
return widget
class Materials(QtCore.QAbstractTableModel):
def __init__(self, materials = [[]], parent = None):
super(Materials, self).__init__()
self.materials = materials
def rowCount(self, parent):
return len(self.materials)
def columnCount(self, parent):
return len(self.materials[0])
def data(self, index, role):
if role == QtCore.Qt.DisplayRole:
row = index.row()
column = index.column()
value = self.materials[row][column]
return value
if role == QtCore.Qt.EditRole:
row = index.row()
column = index.column()
value = self.materials[row][column]
return value
if role == QtCore.Qt.FontRole:
if index.column() == 0:
boldfont = QtGui.QFont()
boldfont.setBold(True)
return boldfont
def setData(self, index, value, role = QtCore.Qt.EditRole):
if role == QtCore.Qt.EditRole:
row = index.row()
column = index.column()
self.materials[row][column] = value
self.dataChanged.emit(index, index)
return True
return False
def flags(self, index):
return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
if __name__ == '__main__':
app = QtWidgets.QApplication([])
application = Mainwindow()
application.show()
sys.exit(app.exec())
A possible solution is to enable the role Qt.CheckStateRole and modify the position of the checkbox using the delegate. For this, the model must also be modified to store the state of the checkbox.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class CustomDelegate(QtWidgets.QStyledItemDelegate):
def initStyleOption(self, option, index):
value = index.data(QtCore.Qt.CheckStateRole)
if value is None:
model = index.model()
model.setData(index, QtCore.Qt.Unchecked, QtCore.Qt.CheckStateRole)
super().initStyleOption(option, index)
option.direction = QtCore.Qt.RightToLeft
option.displayAlignment = QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter
class Mainwindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.table = QtWidgets.QTableView()
self.setCentralWidget(self.table)
self.list = ["item_1", "item_2", "item_3"]
self.data = [
[1, "Blocks γ=500 GOST 31359-2007", self.list[0], 0.18, 0.22],
[2, "Blocks γ=600 GOST 31359-2008", self.list[0], 0.25, 0.27],
[3, "Insulation", self.list[0], 0.041, 0.042],
[3, "Insulation", self.list[0], 0.041, 0.042],
]
self.model = Materials(self.data)
self.table.setModel(self.model)
self.table.setSelectionBehavior(self.table.SelectRows)
self.table.setSelectionMode(self.table.SingleSelection)
for row in range(len(self.model.materials)):
index = self.table.model().index(row, 2)
self.table.setIndexWidget(index, self.setting_combobox(index))
delegate = CustomDelegate(self.table)
self.table.setItemDelegateForColumn(4, delegate)
self.resize(640, 480)
def setting_combobox(self, index):
widget = QtWidgets.QComboBox()
list = self.list
widget.addItems(list)
widget.setCurrentIndex(0)
widget.currentTextChanged.connect(
lambda value: self.model.setData(index, value)
)
return widget
class Materials(QtCore.QAbstractTableModel):
def __init__(self, materials=[[]], parent=None):
super(Materials, self).__init__()
self.materials = materials
self.check_states = dict()
def rowCount(self, parent):
return len(self.materials)
def columnCount(self, parent):
return len(self.materials[0])
def data(self, index, role):
if role == QtCore.Qt.DisplayRole:
row = index.row()
column = index.column()
value = self.materials[row][column]
return value
if role == QtCore.Qt.EditRole:
row = index.row()
column = index.column()
value = self.materials[row][column]
return value
if role == QtCore.Qt.FontRole:
if index.column() == 0:
boldfont = QtGui.QFont()
boldfont.setBold(True)
return boldfont
if role == QtCore.Qt.CheckStateRole:
value = self.check_states.get(QtCore.QPersistentModelIndex(index))
if value is not None:
return value
def setData(self, index, value, role=QtCore.Qt.EditRole):
if role == QtCore.Qt.EditRole:
row = index.row()
column = index.column()
self.materials[row][column] = value
self.dataChanged.emit(index, index, (role,))
return True
if role == QtCore.Qt.CheckStateRole:
self.check_states[QtCore.QPersistentModelIndex(index)] = value
self.dataChanged.emit(index, index, (role,))
return True
return False
def flags(self, index):
return (
QtCore.Qt.ItemIsEditable
| QtCore.Qt.ItemIsEnabled
| QtCore.Qt.ItemIsSelectable
| QtCore.Qt.ItemIsUserCheckable
)
if __name__ == "__main__":
app = QtWidgets.QApplication([])
application = Mainwindow()
application.show()
sys.exit(app.exec())
Hello i started with PyQt5 recently and tried to implement a csv parser:
But i struggled with the descendant of the QAbstractTableModel.
No data in the view!
The tutorial from qt5 (https://doc.qt.io/qt-5/qabstracttablemodel.html) says i have to implement some methods in the TableModel - class.
I think i did that but - no data in the view.
from PyQt5.QtWidgets import \
QApplication, QWidget, QVBoxLayout, QTableView
from PyQt5.QtCore import \
QAbstractTableModel, QVariant, Qt
class TableModel(QAbstractTableModel):
def __init__(self):
super().__init__()
self._data = []
def set(self, data):
self._data = data
def rowCount(self, index):
return len(self._data)
def columnCount(self, index):
return len(self._data[0])
def data(self, index, role=Qt.DisplayRole):
if not index.isValid():
return QVariant()
elif role == Qt.DisplayRole:
row = index.row()
return self._data[row]
else:
return QVariant()
def headerData(self, p_int, Qt_Orientation, role=None):
return self._data[0]
class View(QWidget):
def __init__(self):
super().__init__()
model = TableModel()
model.set(data)
self.tbl = QTableView(self)
self.tbl.setModel(model)
def setup(self):
self.setMinimumHeight(600)
self.setMinimumWidth(800)
self.vlayout = QVBoxLayout(self)
self.vlayout.addWidget(self.tbl)
def main():
import sys
app = QApplication(sys.argv)
window = View()
window.setup()
window.show()
sys.exit(app.exec_())
main()
Some Mock data from here:
data = [f.strip().split(",") for f in """\
id,first_name,last_name,email,gender,ip_address
1,Hillard,Tasseler,htasseler0#google.com.br,Male,104.153.237.243
2,Tyrus,Oley,toley1#ft.com,Male,163.73.24.45
3,Kora,Covil,kcovil2#privacy.gov.au,Female,158.44.166.87
4,Phineas,McEntee,pmcentee3#rambler.ru,Male,71.82.246.45
5,Dottie,Spraging,dspraging4#berkeley.edu,Female,226.138.241.22
6,Andria,Ivatts,aivatts5#about.com,Female,57.5.76.78
7,Missy,Featherstone,mfeatherstone6#unblog.fr,Female,9.56.215.203
8,Anstice,Sargant,asargant7#about.me,Female,36.115.185.109
9,Teresita,Trounce,ttrounce8#myspace.com,Female,240.228.133.166
10,Sib,Thomke,sthomke9#ibm.com,Female,129.191.2.7
11,Amery,Dallander,adallandera#elpais.com,Male,4.115.194.100
12,Rourke,Rowswell,rrowswellb#bloomberg.com,Male,48.111.190.66
13,Cloe,Benns,cbennsc#slideshare.net,Female,142.48.24.44
14,Enos,Fery,eferyd#pen.io,Male,59.19.200.235
15,Russell,Capelen,rcapelene#fc2.com,Male,38.205.20.141""".split()]
The data method must return a value as a string, not a list, in your case self._data[row] is a list so the solution is to use the column to obtain a single element from that list:
def data(self, index, role=Qt.DisplayRole):
if not index.isValid():
return QVariant()
elif role == Qt.DisplayRole:
row = index.row()
col = index.column()
return self._data[row][col]
else:
return QVariant()