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 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())
I have QTableView with QAbstractTableModel and multiple QStyledItemDelegates.
I set these delegates by setStyledItemForColumn.
In this case, my app crashes.
Crash happens when I push 1 key, or try to expand the gui to right.
But if I use one of them, my app goes well.
I think this is a kind of Qt bug.
Do you know somewhat?
from PySide2 import QtWidgets
from PySide2 import QtCore
from PySide2 import QtGui
from PySide2 import QtSql
import os
import PySide2
import sys
dirname = os.path.dirname(PySide2.__file__)
plugin_path = os.path.join(dirname, 'plugins', 'platforms')
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = plugin_path
alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O"]
class IconDelegate(QtWidgets.QStyledItemDelegate):
def initStyleOption(self, option, index):
super(IconDelegate, self).initStyleOption(option, index)
if option.features & QtWidgets.QStyleOptionViewItem.HasDecoration:
s = option.decorationSize
s.setWidth(option.rect.width())
option.decorationSize = s
class Delegate(QtWidgets.QStyledItemDelegate):
def __init__(self, parent=None):
super(Delegate, self).__init__(parent=None)
def initStyleOption(self, option, index):
# super(IconDelegate, self).initStyleOption(option, index)
if index.column() == 6:
if option.features & QtWidgets.QStyleOptionViewItem.HasDecoration:
s = option.decorationSize
s.setWidth(option.rect.width())
option.decorationSize = s
def createEditor(self, parent, option, index):
editor = QtWidgets.QComboBox(parent)
return editor
def setEditorData(self, editor, index):
model = index.model()
items = model.items
text = items[index.row()][index.column()]
editor.setCurrentText(text)
def setModelData(self, editor, model, index):
items = model.items
#
class TableView(QtWidgets.QTableView):
def __init__(self, parent=None):
super(TableView, self).__init__(parent=None)
delegate = Delegate()
self.setItemDelegate(delegate)
#Here is the crash point
# self.setItemDelegateForColumn(6, delegate)
# self.setItemDelegateForColumn(11, IconDelegate())
self.tableModel = TableModel(2, 15)
self.setModel(self.tableModel)
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_1:
self.tableModel.insertRows(0)
class TableItem(object):
def __init__(self, parent=None):
self.root = False
self.word = ""
self.alignment = QtCore.Qt.AlignCenter
self.rule = ""
self.foregroundcolor = QtGui.QColor(QtCore.Qt.black)
self.backgroundcolor = QtGui.QColor(QtCore.Qt.white)
self.font = QtGui.QFont("Meiryo", 14)
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, row = 0, column = 0, parent = None):
super(TableModel, self).__init__(parent = None)
self.items = [[TableItem() for c in range(column)] for r in range(row)]
self.root = QtCore.QModelIndex()
def rowCount(self, parent=QtCore.QModelIndex()):
return len(self.items)
def columnCount(self, parent=QtCore.QModelIndex()):
return 15
def data(self, index, role = QtCore.Qt.DisplayRole):
if not index.isValid():
return None
row = index.row()
column = index.column()
if role == QtCore.Qt.DisplayRole:
item = self.items[row][column]
return item
def headerData(self, section, orientation, role = QtCore.Qt.DisplayRole):
if orientation == QtCore.Qt.Orientation.Horizontal:
if role == QtCore.Qt.DisplayRole:
return alphabet[section]
return super(TableModel, self).headerData(section, orientation, role)
def flags(self, index):
return QtCore.Qt.ItemFlag.ItemIsEditable|QtCore.Qt.ItemFlag.ItemIsEnabled|QtCore.Qt.ItemFlag.ItemIsSelectable
def setData(self, index, value, role=QtCore.Qt.EditRole):
if role == QtCore.Qt.EditRole:
row, column = index.row(), index.column()
self.items[row][column] = value
self.dataChanged.emit(index, index)
return True
elif role == QtCore.Qt.DisplayRole:
row, column = index.row(), index.column()
self.items[row][column] = value
self.dataChanged.emit(index, index)
return True
elif role == QtCore.Qt.FontRole:
string = value.toString()
s = string.split(",")
font = s[0]
self.dataChanged.emit(index, index)
return True
def insertRows(self, position, rows=1, index=QtCore.QModelIndex()):
self.beginInsertRows(QtCore.QModelIndex(), position, position+rows-1)
for row in range(rows):
self.items.insert(position+row, [TableItem() for c in range(self.columnCount())])
self.endInsertRows()
self.emit(QtCore.SIGNAL("dataChanged(QModelIndex, QModelIndex)"), index, index)
self.emit(QtCore.SIGNAL("layoutChanged()"))
return True
def removeRows(self, position, rows=1, index=QtCore.QModelIndex()):
self.beginRemoveRows(QtCore.QModelIndex(), position, position+rows-1)
for row in range(rows):
self.items = self.items[:position] + \
self.items[position + rows:]
self.emit(QtCore.SIGNAL("dataChanged(QModelIndex, QModelIndex)"), index, index)
self.emit(QtCore.SIGNAL("layoutChanged()"))
return True
def main():
if QtWidgets.QApplication.instance() is not None:
app = QtWidgets.QApplication.instance()
else:
app = QtWidgets.QApplication([])
mainwindow = TableView()
mainwindow.show()
sys.exit(QtWidgets.QApplication.exec_())
if __name__ == "__main__":
main()
Explanation
It is not a Qt bug but it is a bug of your own code.
First of all it is recommended that you run your code from the CMD / console so that you get error information, if you do you will see that the error message is:
Traceback (most recent call last):
File "main.py", line 38, in setEditorData
editor.setCurrentText(text)
TypeError: 'PySide2.QtWidgets.QComboBox.setCurrentText' called with wrong argument types:
PySide2.QtWidgets.QComboBox.setCurrentText(TableItem)
Supported signatures:
PySide2.QtWidgets.QComboBox.setCurrentText(str)
The error clearly indicates that the setCurrentText method expects a string but is receiving a TableItem. Why do you receive a TableItem? Well with your code items[index.row()][index.column()] returns a TableItem, assuming you want to get the text "word" then you must use:
def setEditorData(self, editor, index):
model = index.model()
items = model.items
item = items[index.row()][index.column()]
text = item.word
editor.setCurrentText(text)
In both cases (setItemDelegate or setItemD) it causes the error.
But the error still persists when the window is resized since it is caused by the other delegate. Since you are partially overriding a delegate then the other party continues to use the generic information, for example expect index.data(Qt.DisplayRole) to return a string but in your case return a TableItem:
def data(self, index, role = QtCore.Qt.DisplayRole):
if not index.isValid():
return None
row = index.row()
column = index.column()
if role == QtCore.Qt.DisplayRole:
item = self.items[row][column]
return item
In conclusion, the OP have not correctly used the default roles, causing delegates who use this information to obtain the incorrect data.
Solution
Considering all of the above, I have corrected many errors that I have not mentioned previously because many are trivial or are out of topic, obtaining the following code:
from PySide2 import QtWidgets
from PySide2 import QtCore
from PySide2 import QtGui
from PySide2 import QtSql
import os
import PySide2
import sys
dirname = os.path.dirname(PySide2.__file__)
plugin_path = os.path.join(dirname, "plugins", "platforms")
os.environ["QT_QPA_PLATFORM_PLUGIN_PATH"] = plugin_path
alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O"]
class IconDelegate(QtWidgets.QStyledItemDelegate):
def initStyleOption(self, option, index):
super(IconDelegate, self).initStyleOption(option, index)
if option.features & QtWidgets.QStyleOptionViewItem.HasDecoration:
s = option.decorationSize
s.setWidth(option.rect.width())
option.decorationSize = s
class Delegate(QtWidgets.QStyledItemDelegate):
def initStyleOption(self, option, index):
if option.features & QtWidgets.QStyleOptionViewItem.HasDecoration:
s = option.decorationSize
s.setWidth(option.rect.width())
option.decorationSize = s
def createEditor(self, parent, option, index):
editor = QtWidgets.QComboBox(parent)
return editor
#
class TableView(QtWidgets.QTableView):
def __init__(self, parent=None):
super(TableView, self).__init__(parent=None)
delegate = Delegate(self)
# self.setItemDelegate(delegate)
# Here is the crash point
self.setItemDelegateForColumn(6, delegate)
icon_delegate = IconDelegate(self)
self.setItemDelegateForColumn(11, icon_delegate)
self.tableModel = TableModel(2, 15)
self.setModel(self.tableModel)
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_1:
self.tableModel.insertRows(0)
class TableItem(object):
def __init__(self, parent=None):
self.root = False
self.word = ""
self.alignment = QtCore.Qt.AlignCenter
self.rule = ""
self.foregroundcolor = QtGui.QColor(QtCore.Qt.black)
self.backgroundcolor = QtGui.QColor(QtCore.Qt.white)
self.font = QtGui.QFont("Meiryo", 14)
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, row=0, column=0, parent=None):
super(TableModel, self).__init__(parent=None)
self.items = [[TableItem() for c in range(column)] for r in range(row)]
def rowCount(self, parent=QtCore.QModelIndex()):
return len(self.items)
def columnCount(self, parent=QtCore.QModelIndex()):
if self.items:
return len(self.items[0])
return 0
def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid():
return None
row = index.row()
column = index.column()
if 0 <= row < self.rowCount() and 0 <= column < self.columnCount():
item = self.items[row][column]
if role == QtCore.Qt.DisplayRole:
text = item.word
return text
elif role == QtCore.Qt.EditRole:
return item
def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
if orientation == QtCore.Qt.Orientation.Horizontal:
if role == QtCore.Qt.DisplayRole and section < len(alphabet):
return alphabet[section]
return super(TableModel, self).headerData(section, orientation, role)
def flags(self, index):
return (
QtCore.Qt.ItemFlag.ItemIsEditable
| QtCore.Qt.ItemFlag.ItemIsEnabled
| QtCore.Qt.ItemFlag.ItemIsSelectable
)
def setData(self, index, value, role=QtCore.Qt.EditRole):
if role == QtCore.Qt.EditRole:
row, column = index.row(), index.column()
self.items[row][column].word = value
self.dataChanged.emit(index, index)
return True
elif role == QtCore.Qt.DisplayRole:
row, column = index.row(), index.column()
self.items[row][column].word = value
self.dataChanged.emit(index, index)
return True
return False
def insertRows(self, position, rows=1, index=QtCore.QModelIndex()):
self.beginInsertRows(QtCore.QModelIndex(), position, position + rows - 1)
for row in range(rows):
self.items.insert(
position + row, [TableItem() for c in range(self.columnCount())]
)
self.endInsertRows()
self.emit(QtCore.SIGNAL("dataChanged(QModelIndex, QModelIndex)"), index, index)
self.emit(QtCore.SIGNAL("layoutChanged()"))
return True
def removeRows(self, position, rows=1, index=QtCore.QModelIndex()):
self.beginRemoveRows(QtCore.QModelIndex(), position, position + rows - 1)
for row in range(rows):
self.items = self.items[:position] + self.items[position + rows :]
self.emit(QtCore.SIGNAL("dataChanged(QModelIndex, QModelIndex)"), index, index)
self.emit(QtCore.SIGNAL("layoutChanged()"))
return True
def main():
if QtWidgets.QApplication.instance() is not None:
app = QtWidgets.QApplication.instance()
else:
app = QtWidgets.QApplication([])
mainwindow = TableView()
mainwindow.show()
sys.exit(QtWidgets.QApplication.exec_())
if __name__ == "__main__":
main()
hi i've tried all i can think of and had looked at hundreds of stack overflow questions about tables and delegate's, and scratched my head for hours looking at the documentation trying to understand the c++ language and i have not read anything clearly stating that there's limits to the of amount delegate's a table view can take and not take, now i hope i can say i've got a firm understanding of the basic's in pyside2 and pyqt5 especially with tables and models but the delegates is a bit mind boggling, i've gotten this far based on people's questions mostly from stack overflow so this is my first attempt to ask any help..
import pandas as pd
from PySide2 import QtWidgets
from PySide2.QtCore import (Qt, QAbstractTableModel, QModelIndex, QEvent, QPersistentModelIndex,
QSortFilterProxyModel,
QTimer, Slot)
from PySide2.QtWidgets import QTableView, QAbstractItemView, QComboBox, QItemDelegate
class ScheduleModel(QAbstractTableModel):
def __init__(self, schedules_list=None, parent=None):
super(ScheduleModel, self).__init__(parent)
if schedules_list is None:
self.schedules_list = []
else:
self.schedules_list = schedules_list
def rowCount(self, index=QModelIndex()):
return self.schedules_list.shape[0]
def columnCount(self, index=QModelIndex()):
return self.schedules_list.shape[1]
def data(self, index, role=Qt.DisplayRole):
col = index.column()
if index.isValid():
if role == Qt.DisplayRole:
value = self.schedules_list.iloc[index.row(), index.column()]
return str(self.schedules_list.iloc[index.row(), index.column()])
return None
def headerData(self, section, orientation, role):
# section is the index of the column/row.
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self.schedules_list.columns[section]
if orientation == Qt.Vertical:
return str(self.schedules_list.index[section])
def setData(self, index, value, role=Qt.EditRole):
if role != Qt.EditRole:
return False
if index.isValid() and 0 <= index.row() < len(self.schedules_list):
self.schedules_list.iloc[index.row(), index.column()] = value
if self.data(index, Qt.DisplayRole) == value:
self.dataChanged.emit(index, index, (Qt.EditRole,))
return True
return False
def flags(self, index):
if 1 <= index.column() <= 7:
return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable
if index.column() == 5:
return Qt.ItemIsEditable | Qt.ItemIsUserCheckable | Qt.ItemIsSelectable
elif index.column() == 1 and index.column() == 7:
return Qt.DecorationRole
else:
return Qt.ItemIsSelectable
class ClickDelegate(QtWidgets.QStyledItemDelegate):
blankText = '<Click here to add path>'
def openFileDialog(self, lineEdit):
if not self.blankText.startswith(lineEdit.text()):
currentPath = lineEdit.text()
else:
currentPath = ''
path, _ = QtWidgets.QFileDialog.getOpenFileName(lineEdit.window(),
'Select file', currentPath)
if path:
lineEdit.setText(path)
def createEditor(self, parent, option, index):
editor = QtWidgets.QWidget(parent)
layout = QtWidgets.QHBoxLayout(editor)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
editor.lineEdit = QtWidgets.QLineEdit(self.blankText)
layout.addWidget(editor.lineEdit)
editor.setFocusProxy(editor.lineEdit)
editor.lineEdit.installEventFilter(self)
button = QtWidgets.QToolButton(text='...')
layout.addWidget(button)
button.setFocusPolicy(Qt.NoFocus)
button.clicked.connect(lambda: self.openFileDialog(editor.lineEdit))
return editor
def setEditorData(self, editor, index):
if index.data():
editor.lineEdit.setText(str(index.data()))
editor.lineEdit.selectAll()
def setModelData(self, editor, model, index):
if not editor.lineEdit.text():
model.setData(index, None)
elif not self.blankText.startswith(editor.lineEdit.text()):
model.setData(index, editor.lineEdit.text())
def initStyleOption(self, option, index):
super(ClickDelegate, self).initStyleOption(option, index)
if not option.text:
option.text = self.blankText
def eventFilter(self, source, event):
if isinstance(source, QtWidgets.QLineEdit):
if (event.type() == QEvent.MouseButtonPress and
source.hasSelectedText() and
self.blankText.startswith(source.text())):
res = super(ClickDelegate, self).eventFilter(source, event)
source.clear()
return res
elif event.type() == QEvent.KeyPress and event.key() in (
Qt.Key_Escape, Qt.Key_Tab, Qt.Key_Backtab):
return False
return super(ClickDelegate, self).eventFilter(source, event)
def checkIndex(self, table, index):
if index in table.selectedIndexes() and index == table.currentIndex():
table.edit(index)
def editorEvent(self, event, model, option, index):
if (event.type() == QEvent.MouseButtonPress and
event.button() == Qt.LeftButton and
index in option.widget.selectedIndexes()):
table = option.widget
QTimer.singleShot(0, lambda: self.checkIndex(table, index))
return super(ClickDelegate, self).editorEvent(event, model, option, index)
class CheckBoxDelegate(QtWidgets.QItemDelegate):
"""
A delegate that places a fully functioning QCheckBox cell of the column to which it's applied.
"""
def __init__(self, parent):
QtWidgets.QItemDelegate.__init__(self, parent)
def createEditor(self, parent, option, index):
"""
Important, otherwise an editor is created if the user clicks in this cell.
"""
return None
def paint(self, painter, option, index):
"""
Paint a checkbox without the label.
"""
self.drawCheck(painter, option, option.rect,
Qt.Unchecked if int(index.data()) == 0 else Qt.Checked)
def editorEvent(self, event, model, option, index):
'''
Change the data in the model and the state of the checkbox
if the user presses the left mousebutton and this cell is editable. Otherwise do nothing.
'''
if not int(index.flags() and Qt.ItemIsEditable) > 0:
return False
if event.type() == QEvent.MouseButtonRelease and event.button() == Qt.LeftButton:
# Change the checkbox-state
self.setModelData(None, model, index)
return True
return False
def setModelData(self, editor, model, index):
'''
The user wanted to change the old state in the opposite.
'''
model.setData(index, 1 if int(index.data()) == 0 else 0, Qt.EditRole)
class DoubleSpinBoxDelegate(QtWidgets.QStyledItemDelegate):
"""A delegate class displaying a double spin box."""
def __init__(self, parent=None, minimum=0.0, maximum=100.0, step=0.01):
QtWidgets.QStyledItemDelegate.__init__(self, parent)
self._min = minimum
self._max = maximum
self._step = step
def createEditor(self, parent, option, index):
editor = QtWidgets.QDoubleSpinBox(parent)
editor.setMinimum(self._min)
editor.setMaximum(self._max)
editor.setSingleStep(self._step)
editor.setAccelerated(True)
editor.installEventFilter(self)
return editor
def setEditorData(self, spinBox, index):
value = float(index.model().data(index, Qt.DisplayRole))
spinBox.setValue(value)
def setModelData(self, spinBox, model, index):
value = spinBox.value()
model.setData(index, value)
def updateEditorGeometry(self, editor, option, index):
editor.setGeometry(option.rect)
class ComboBoxDelegate(QItemDelegate):
def __init__(self, parent=None):
super(ComboBoxDelegate, self).__init__(parent)
self.items = []
def setItems(self, items):
self.items = items
def createEditor(self, parent, option, index):
combo = QComboBox(parent)
li = []
for item in self.items:
li.append(item)
combo.addItems(li)
combo.currentIndexChanged.connect(self.currentIndexChanged)
return combo
def setEditorData(self, editor, index):
editor.blockSignals(True)
text = index.model().data(index, Qt.DisplayRole)
try:
i = self.items.index(text)
except ValueError:
i = 0
editor.setCurrentIndex(i)
def setModelData(self, editor, model, index):
# model.setData(index, editor.currentIndex(), Qt.EditRole)
model.setData(index, editor.currentText())
def updateEditorGeometry(self, editor, option, index):
editor.setGeometry(option.rect)
#Slot()
def currentIndexChanged(self):
self.commitData.emit(self.sender())
class SchedulesViewer(QTableView):
# selectionChanged = Signal(QItemSelection)
# data_changed = Signal(QModelIndex, QModelIndex)
def __init__(self, parent=None):
QTableView.__init__(self, parent)
# self.setContextMenuPolicy(Qt.CustomContextMenu)
# self.customContextMenuRequested.connect(self.schedule_context_menu)
address = {'idx': '1',
'presets': 'presets',
'selected_source': 'get_source',
'selected_destinations': 'selected_destinations',
'interval': '0400',
'active': '1',
'priority': 'high',
'categories': 'programming',
'last_total': '222',
}
self.schedule_model = ScheduleModel(pd.DataFrame([address]))
self.proxyModel = QSortFilterProxyModel(self)
self.proxyModel.setSourceModel(self.schedule_model)
self.proxyModel.setDynamicSortFilter(True)
self.setModel(self.proxyModel)
**"""
HAVING LIMITS TO THE AMOUNT OF WIDGETS TABLE VIEW CAN HANDEL
"""
dialog_delegate = ClickDelegate(self)
self.setItemDelegateForColumn(2, dialog_delegate)
self.setItemDelegateForColumn(3, dialog_delegate)
# spin_delegate = DoubleSpinBoxDelegate()
# self.setItemDelegateForColumn(4, spin_delegate)
# CheckBox = CheckBoxDelegate(None)
# self.setItemDelegateForColumn(5, CheckBox)
data = ['programming', 'game_build', 'other']
combo_delegate = ComboBoxDelegate()
combo_delegate.setItems([str(row) for row in data])
self.setItemDelegateForColumn(6, combo_delegate)**
self.setSortingEnabled(True)
self.setSelectionBehavior(QAbstractItemView.SelectRows)
self.horizontalHeader().setStretchLastSection(True)
self.verticalHeader().hide()
self.setSelectionMode(QAbstractItemView.SingleSelection)
self.proxyModel.sort(0, Qt.AscendingOrder)
self.setSelectionBehavior(QAbstractItemView.SelectRows)
self.setEditTriggers(QAbstractItemView.DoubleClicked)
self.setSelectionMode(QAbstractItemView.SingleSelection)
# self.selectionModel().selectionChanged.connect(self.selectionChanged)
self.show()
if __name__ == "__main__":
import sys
from PySide2.QtWidgets import QApplication
app = QApplication(sys.argv)
addressWidget = SchedulesViewer()
addressWidget.show()
sys.exit(app.exec_())
so please would someone help me understand what i'am i missing or not understanding, all that i want to achieve is to add the delegate's that have been hashed out and make it a editable table, but if i add either the spinbox or the checkbox delegate the app freezes and crashes so is there a limit as to how many delegate's the table view can handle or what i'am i doing wrong? Any help would be much appreciated please and thank you in advance..
Thanks to musicamante that pointed out so freindly my simple mistake of overlooking the obvious of the too self's missing to make all the delegates members of the instance and i have tested and it works so here is the code..
import pandas as pd
from PySide2 import QtWidgets
from PySide2.QtCore import (Qt, QAbstractTableModel, QModelIndex, QEvent,
QPersistentModelIndex,
QSortFilterProxyModel,
QTimer, Slot)
from PySide2.QtWidgets import QTableView, QAbstractItemView, QComboBox, QItemDelegate
class ScheduleModel(QAbstractTableModel):
def __init__(self, schedules_list=None, parent=None):
super(ScheduleModel, self).__init__(parent)
if schedules_list is None:
self.schedules_list = []
else:
self.schedules_list = schedules_list
def rowCount(self, index=QModelIndex()):
return self.schedules_list.shape[0]
def columnCount(self, index=QModelIndex()):
return self.schedules_list.shape[1]
def data(self, index, role=Qt.DisplayRole):
col = index.column()
if index.isValid():
if role == Qt.DisplayRole:
value = self.schedules_list.iloc[index.row(), index.column()]
return str(self.schedules_list.iloc[index.row(), index.column()])
return None
def headerData(self, section, orientation, role):
# section is the index of the column/row.
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self.schedules_list.columns[section]
if orientation == Qt.Vertical:
return str(self.schedules_list.index[section])
def setData(self, index, value, role=Qt.EditRole):
if role != Qt.EditRole:
return False
if index.isValid() and 0 <= index.row() < len(self.schedules_list):
self.schedules_list.iloc[index.row(), index.column()] = value
if self.data(index, Qt.DisplayRole) == value:
self.dataChanged.emit(index, index, (Qt.EditRole,))
return True
return False
def flags(self, index):
if 1 <= index.column() <= 7:
return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable
if index.column() == 5:
return Qt.ItemIsEditable | Qt.ItemIsUserCheckable | Qt.ItemIsSelectable
elif index.column() == 1 and index.column() == 7:
return Qt.DecorationRole
else:
return Qt.ItemIsSelectable
class ClickDelegate(QtWidgets.QStyledItemDelegate):
blankText = '<Click here to add path>'
def openFileDialog(self, lineEdit):
if not self.blankText.startswith(lineEdit.text()):
currentPath = lineEdit.text()
else:
currentPath = ''
path, _ = QtWidgets.QFileDialog.getOpenFileName(lineEdit.window(),
'Select file', currentPath)
if path:
lineEdit.setText(path)
def createEditor(self, parent, option, index):
editor = QtWidgets.QWidget(parent)
layout = QtWidgets.QHBoxLayout(editor)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
editor.lineEdit = QtWidgets.QLineEdit(self.blankText)
layout.addWidget(editor.lineEdit)
editor.setFocusProxy(editor.lineEdit)
editor.lineEdit.installEventFilter(self)
button = QtWidgets.QToolButton(text='...')
layout.addWidget(button)
button.setFocusPolicy(Qt.NoFocus)
button.clicked.connect(lambda: self.openFileDialog(editor.lineEdit))
return editor
def setEditorData(self, editor, index):
if index.data():
editor.lineEdit.setText(str(index.data()))
editor.lineEdit.selectAll()
def setModelData(self, editor, model, index):
if not editor.lineEdit.text():
model.setData(index, None)
elif not self.blankText.startswith(editor.lineEdit.text()):
model.setData(index, editor.lineEdit.text())
def initStyleOption(self, option, index):
super(ClickDelegate, self).initStyleOption(option, index)
if not option.text:
option.text = self.blankText
def eventFilter(self, source, event):
if isinstance(source, QtWidgets.QLineEdit):
if (event.type() == QEvent.MouseButtonPress and
source.hasSelectedText() and
self.blankText.startswith(source.text())):
res = super(ClickDelegate, self).eventFilter(source, event)
source.clear()
return res
elif event.type() == QEvent.KeyPress and event.key() in (
Qt.Key_Escape, Qt.Key_Tab, Qt.Key_Backtab):
return False
return super(ClickDelegate, self).eventFilter(source, event)
def checkIndex(self, table, index):
if index in table.selectedIndexes() and index == table.currentIndex():
table.edit(index)
def editorEvent(self, event, model, option, index):
if (event.type() == QEvent.MouseButtonPress and
event.button() == Qt.LeftButton and
index in option.widget.selectedIndexes()):
table = option.widget
QTimer.singleShot(0, lambda: self.checkIndex(table, index))
return super(ClickDelegate, self).editorEvent(event, model, option, index)
class CheckBoxDelegate(QtWidgets.QItemDelegate):
"""
A delegate that places a fully functioning QCheckBox cell of the column to which
it's applied.
"""
def __init__(self, parent):
QtWidgets.QItemDelegate.__init__(self, parent)
def createEditor(self, parent, option, index):
"""
Important, otherwise an editor is created if the user clicks in this cell.
"""
return None
def paint(self, painter, option, index):
"""
Paint a checkbox without the label.
"""
self.drawCheck(painter, option, option.rect,
Qt.Unchecked if int(index.data()) == 0 else Qt.Checked)
def editorEvent(self, event, model, option, index):
'''
Change the data in the model and the state of the checkbox
if the user presses the left mousebutton and this cell is editable. Otherwise
do nothing.
'''
if not int(index.flags() and Qt.ItemIsEditable) > 0:
return False
if event.type() == QEvent.MouseButtonRelease and event.button() ==
Qt.LeftButton:
# Change the checkbox-state
self.setModelData(None, model, index)
return True
return False
def setModelData(self, editor, model, index):
'''
The user wanted to change the old state in the opposite.
'''
model.setData(index, 1 if int(index.data()) == 0 else 0, Qt.EditRole)
class DoubleSpinBoxDelegate(QtWidgets.QStyledItemDelegate):
"""A delegate class displaying a double spin box."""
def __init__(self, parent=None, minimum=0.0, maximum=100.0, step=0.01):
QtWidgets.QStyledItemDelegate.__init__(self, parent)
self._min = minimum
self._max = maximum
self._step = step
def createEditor(self, parent, option, index):
editor = QtWidgets.QDoubleSpinBox(parent)
editor.setMinimum(self._min)
editor.setMaximum(self._max)
editor.setSingleStep(self._step)
editor.setAccelerated(True)
editor.installEventFilter(self)
return editor
def setEditorData(self, spinBox, index):
value = float(index.model().data(index, Qt.DisplayRole))
spinBox.setValue(value)
def setModelData(self, spinBox, model, index):
value = spinBox.value()
model.setData(index, value)
def updateEditorGeometry(self, editor, option, index):
editor.setGeometry(option.rect)
class ComboBoxDelegate(QItemDelegate):
def __init__(self, parent=None):
super(ComboBoxDelegate, self).__init__(parent)
self.items = []
def setItems(self, items):
self.items = items
def createEditor(self, parent, option, index):
combo = QComboBox(parent)
li = []
for item in self.items:
li.append(item)
combo.addItems(li)
combo.currentIndexChanged.connect(self.currentIndexChanged)
return combo
def setEditorData(self, editor, index):
editor.blockSignals(True)
text = index.model().data(index, Qt.DisplayRole)
try:
i = self.items.index(text)
except ValueError:
i = 0
editor.setCurrentIndex(i)
def setModelData(self, editor, model, index):
# model.setData(index, editor.currentIndex(), Qt.EditRole)
model.setData(index, editor.currentText())
def updateEditorGeometry(self, editor, option, index):
editor.setGeometry(option.rect)
#Slot()
def currentIndexChanged(self):
self.commitData.emit(self.sender())
class SchedulesViewer(QTableView):
# selectionChanged = Signal(QItemSelection)
# data_changed = Signal(QModelIndex, QModelIndex)
def __init__(self, parent=None):
QTableView.__init__(self, parent)
# self.setContextMenuPolicy(Qt.CustomContextMenu)
# self.customContextMenuRequested.connect(self.schedule_context_menu)
address = {'idx': '1',
'presets': 'presets',
'selected_source': 'get_source',
'selected_destinations': 'selected_destinations',
'interval': '0400',
'active': '1',
'priority': 'high',
'categories': 'programming',
'last_total': '222',
}
self.schedule_model = ScheduleModel(pd.DataFrame([address]))
self.proxyModel = QSortFilterProxyModel(self)
self.proxyModel.setSourceModel(self.schedule_model)
self.proxyModel.setDynamicSortFilter(True)
self.setModel(self.proxyModel)
"""
HAVING LIMITS TO THE AMOUNT OF WIDGETS TABLE VIEW CAN HANDEL
"""
self.setItemDelegateForColumn(2, ClickDelegate(self))
self.setItemDelegateForColumn(3, ClickDelegate(self))
self.setItemDelegateForColumn(4, DoubleSpinBoxDelegate(self))
self.setItemDelegateForColumn(5, CheckBoxDelegate(self))
data = ['programming', 'game_build', 'other']
combo_delegate = ComboBoxDelegate(self)
combo_delegate.setItems([str(row) for row in data])
self.setItemDelegateForColumn(6, combo_delegate)
self.setSortingEnabled(True)
self.setSelectionBehavior(QAbstractItemView.SelectRows)
self.horizontalHeader().setStretchLastSection(True)
self.verticalHeader().hide()
self.setSelectionMode(QAbstractItemView.SingleSelection)
self.proxyModel.sort(0, Qt.AscendingOrder)
self.setSelectionBehavior(QAbstractItemView.SelectRows)
self.setEditTriggers(QAbstractItemView.DoubleClicked)
self.setSelectionMode(QAbstractItemView.SingleSelection)
# self.selectionModel().selectionChanged.connect(self.selectionChanged)
self.show()
if __name__ == "__main__":
import sys
from PySide2.QtWidgets import QApplication
app = QApplication(sys.argv)
addressWidget = SchedulesViewer()
addressWidget.show()
sys.exit(app.exec_())
I have QTableView which views a pandas table. The first row has QComboBox delegates. When I sort the table by a column the delegates disappear.
A working example of my code is below.
import sys
import pandas as pd
import numpy as np
from PyQt5.QtCore import (QAbstractTableModel, Qt, pyqtProperty, pyqtSlot,
QVariant, QModelIndex)
from PyQt5.QtWidgets import (QItemDelegate, QComboBox, QMainWindow, QTableView,
QApplication)
class DataFrameModel(QAbstractTableModel):
DtypeRole = Qt.UserRole + 1000
ValueRole = Qt.UserRole + 1001
ActiveRole = Qt.UserRole + 1
def __init__(self, df=pd.DataFrame(), parent=None):
super(DataFrameModel, self).__init__(parent)
self._dataframe = df
def setDataFrame(self, dataframe):
self.beginResetModel()
self._dataframe = dataframe.copy()
self.endResetModel()
def dataFrame(self):
return self._dataframe
dataFrame = pyqtProperty(pd.DataFrame, fget=dataFrame, fset=setDataFrame)
#pyqtSlot(int, Qt.Orientation, result=str)
def headerData(self, section, orientation, role=Qt.DisplayRole):
if role != Qt.DisplayRole:
return QVariant()
if orientation == Qt.Horizontal:
try:
return self._dataframe.columns.tolist()[section]
except (IndexError, ):
return QVariant()
elif orientation == Qt.Vertical:
try:
if section in [0]:
pass
else:
return self._dataframe.index.tolist()[section - 1]
except (IndexError, ):
return QVariant()
def rowCount(self, parent=QModelIndex()):
if parent.isValid():
return 0
return len(self._dataframe.index)
def columnCount(self, parent=QModelIndex()):
if parent.isValid():
return 0
return self._dataframe.columns.size
def data(self, index, role=Qt.DisplayRole):
if not index.isValid() or not (0 <= index.row() < self.rowCount()
and 0 <= index.column() <
self.columnCount()):
return QVariant()
row = self._dataframe.index[index.row()]
col = self._dataframe.columns[index.column()]
dt = self._dataframe[col].dtype
val = self._dataframe.iloc[row][col]
if role == Qt.DisplayRole:
return str(val)
elif role == DataFrameModel.ValueRole:
return val
if role == DataFrameModel.DtypeRole:
return dt
return QVariant()
def roleNames(self):
roles = {
Qt.DisplayRole: b'display',
DataFrameModel.DtypeRole: b'dtype',
DataFrameModel.ValueRole: b'value'
}
return roles
def setData(self, index, value, role):
col = index.column()
row = index.row()
if index.row() == 0:
if isinstance(value, QVariant):
value = value.value()
if hasattr(value, 'toPyObject'):
value = value.toPyObject()
self._dataframe.iloc[row, col] = value
self.dataChanged.emit(index, index, (Qt.DisplayRole,))
else:
try:
value = eval(value)
if not isinstance(
value,
self._dataframe.applymap(type).iloc[row, col]):
value = self._dataframe.iloc[row, col]
except Exception as e:
value = self._dataframe.iloc[row, col]
self._dataframe.iloc[row, col] = value
self.dataChanged.emit(index, index, (Qt.DisplayRole,))
return True
def flags(self, index):
return Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable
def sort(self, column, order):
self.layoutAboutToBeChanged.emit()
col_name = self._dataframe.columns.tolist()[column]
sheet1 = self._dataframe.iloc[:1, :]
sheet2 = self._dataframe.iloc[1:, :].sort_values(
col_name, ascending=order == Qt.AscendingOrder, inplace=False)
sheet2.reset_index(drop=True, inplace=True)
sheet3 = pd.concat([sheet1, sheet2], ignore_index=True)
self.setDataFrame(sheet3)
self.layoutChanged.emit()
class ComboBoxDelegate(QItemDelegate):
def __init__(self, owner, choices):
super().__init__(owner)
self.items = choices
def createEditor(self, parent, option, index):
editor = QComboBox(parent)
editor.addItems(self.items)
editor.currentIndexChanged.connect(self.currentIndexChanged)
return editor
def paint(self, painter, option, index):
if isinstance(self.parent(), QItemDelegate):
self.parent().openPersistentEditor(0, index)
QItemDelegate.paint(self, painter, option, index)
def setModelData(self, editor, model, index):
value = editor.currentText()
model.setData(index, value, Qt.EditRole)
def updateEditorGeometry(self, editor, option, index):
editor.setGeometry(option.rect)
#pyqtSlot()
def currentIndexChanged(self):
self.commitData.emit(self.sender())
class MainWindow(QMainWindow):
def __init__(self, pandas_sheet):
super().__init__()
self.pandas_sheet = pandas_sheet
for i in range(1):
self.pandas_sheet.loc[-1] = [''] * len(self.pandas_sheet.columns.values)
self.pandas_sheet.index = self.pandas_sheet.index + 1
self.pandas_sheet = self.pandas_sheet.sort_index()
self.table = QTableView()
self.setCentralWidget(self.table)
delegate = ComboBoxDelegate(self.table,
['m1', 'm2', 'm3'])
model = DataFrameModel(self.pandas_sheet, self)
self.table.setModel(model)
self.table.setSortingEnabled(True)
self.table.setItemDelegateForRow(0, delegate)
for i in range(model.columnCount()):
ix = model.index(0, i)
self.table.openPersistentEditor(ix)
self.table.resizeColumnsToContents()
self.table.resizeRowsToContents()
if __name__ == '__main__':
df = pd.DataFrame({'a': ['col0'] * 5,
'b': np.arange(5),
'c': np.random.rand(5)})
app = QApplication(sys.argv)
window = MainWindow(df)
window.show()
sys.exit(app.exec_())
The image below shows the table before sorting.
The image below after sorting the table by one of the columns.
I would like to have the style for the first row the same before and after sorting by any column. Is this possible?
By default the editors are not displayed unless the user interacts with the items using the events indicated in the flags assigned to editTriggers or if you force them to open them using openPersistentEditor().
Considering the last option you can automate the task shown but for this the view must be accessible from the delegate's paint method since it is always called by what a solution is to pass it as a parent (it seems that you are trying to implement) and use the openPersistentEditor() if it is the view, in your case there is an error since the parent is not a QItemDelegate but inherits from QAbstractItemView, in addition you must pass the QModelIndex.
Considering the above, the solution is:
def paint(self, painter, option, index):
if isinstance(self.parent(), QAbstractItemView):
self.parent().openPersistentEditor(index)
So with the above every time the delegates are repainted (for example after a sorting) openPersistentEditor() will be called making the editors visible.
Update:
The editor must save the information in the QModelIndex roles through setModelData and retrieve them using setEditorData, in your case you do not implement the second one so the editor will not obtain the information when the editor is created again. In addition setModelData saves the information in Qt::EditRole but in your model it does not handle that role so you must use Qt::DisplayRole.
Considering the above, the solution is:
class ComboBoxDelegate(QItemDelegate):
def __init__(self, parent, choices):
super().__init__(parent)
self.items = choices
def createEditor(self, parent, option, index):
editor = QComboBox(parent)
editor.addItems(self.items)
editor.currentIndexChanged.connect(self.currentIndexChanged)
return editor
def paint(self, painter, option, index):
if isinstance(self.parent(), QAbstractItemView):
self.parent().openPersistentEditor(index)
def setModelData(self, editor, model, index):
value = editor.currentText()
model.setData(index, value, Qt.DisplayRole)
def setEditorData(self, editor, index):
text = index.data(Qt.DisplayRole) or ""
editor.setCurrentText(text)
def updateEditorGeometry(self, editor, option, index):
editor.setGeometry(option.rect)
#pyqtSlot()
def currentIndexChanged(self):
self.commitData.emit(self.sender())