Change background of model index for QAbstractTableModel in PySide6 - python

I would like to change the background color of specific index on my table, but only after a specific task is completed.
I know that I can use the Background role to change the color in my Table model, but I want to change the background color on external factors and not based on changes to the table itself. For example, the code below shows a basic example of a QTableView with 6 rows displayed in a QWidget. Inside the main app I am able to change the text of specific indexes using setData as seen below.
model.setData(model.index(2, 0), "Task Complete")
Here is the full code:
import sys
from PySide6.QtWidgets import (
QApplication, QWidget, QTableView, QVBoxLayout
)
from PySide6.QtCore import Qt, QAbstractTableModel
from PySide6.QtGui import QBrush
class TableModel(QAbstractTableModel):
def __init__(self, data):
super().__init__()
self._data = data
def data(self, index, role=Qt.DisplayRole):
# display data
if role == Qt.DisplayRole:
try:
return self._data[index.row()][index.column()]
except IndexError:
return ''
def setData(self, index, value, role=Qt.EditRole):
if role in (Qt.DisplayRole, Qt.EditRole):
# if value is blank
if not value:
return False
self._data[index.row()][index.column()] = value
self.dataChanged.emit(index, index)
return True
def rowCount(self, index):
return len(self._data)
def columnCount(self, index):
return len(self._data[0])
def flags(self, index):
return super().flags(index) | Qt.ItemIsEditable
class MainApp(QWidget):
def __init__(self):
super().__init__()
self.window_width, self.window_height = 200, 250
self.setMinimumSize(self.window_width, self.window_height)
self.layout = {}
self.layout['main'] = QVBoxLayout()
self.setLayout(self.layout['main'])
self.table = QTableView()
self.layout['main'].addWidget(self.table)
model = TableModel(data)
self.table.setModel(model)
# THIS IS WHERE THE QUESTION IS
model.setData(model.index(2, 0), "Task Complete") # Change background color instead of text
model.setData(model.index(5, 0), "Task Complete") # Change background color instead of text
if __name__ == '__main__':
data = [
["Task 1"],
["Task 2"],
["Task 3"],
["Task 4"],
["Task 5"],
["Task 6"],
]
app = QApplication(sys.argv)
myApp = MainApp()
myApp.show()
try:
sys.exit(app.exec())
except SystemExit:
print('Closing Window...')
I have tried to change the setData function to use the Qt.BackgroundRole instead of Qt.EditRole, but that does not work for changing the color. The result is that the code runs, but nothing happens.
I want to be able to fill the background with whatever color I choose based on the specific index I pick. However, I want this code to reside inside the MainApp class and not in the TableModel Class.
Suggestions Tried
Added code to data()
if role == Qt.BackgroundRole:
return QBrush(Qt.green)
Changed setData()
def setData(self, index, value, role=Qt.BackgroundRole):
if role in (Qt.DisplayRole, Qt.BackgroundRole):
# if value is blank
if not value:
return False
self._data[index.row()][index.column()] = value
self.dataChanged.emit(index, index)
return True
Changed setData in MainApp too
model.setData(model.index(5, 0), QBrush(Qt.green))
This resulted in highlighting the entire table in green instead of specific index.

If you want to set different colors for each index, you must store the color information in another data structure and return the corresponding value for the index.
Both data() and setData() must access different values depending on the role (see the documentation about item roles), meaning that you must not use self._data indiscriminately for anything role. If you set the color for a row/column in the same data structure you use for the text, then the text is lost.
A simple solution is to create a list of lists that has the same size of the source data, using None as default value.
class TableModel(QAbstractTableModel):
def __init__(self, data):
super().__init__()
self._data = data
rows = len(data)
cols = len(data[0])
self._backgrounds = [[None] * cols for _ in range(rows)]
def data(self, index, role=Qt.DisplayRole):
if not index.isValid():
return
elif role in (Qt.DisplayRole, Qt.EditRole):
return self._data[index.row()][index.column()]
elif role == Qt.BackgroundRole:
return self._backgrounds[index.row()][index.column()]
def setData(self, index, value, role=Qt.EditRole):
if (
not index.isValid()
or index.row() >= len(self._data)
or index.column() >= len(self._data[0])
):
return False
if role == Qt.EditRole:
self._data[index.row()][index.column()] = value
elif role == Qt.BackgroundRole:
self._backgrounds[index.row()][index.column()] = value
else:
return False
self.dataChanged.emit(index, index, [role])
return True
Note: you should always ensure that data has at least one row, otherwise columnCount() will raise an exception.
Then, to update the color, you must also use the proper role:
model.setData(model.index(5, 0), QBrush(Qt.green), Qt.BackgroundRole)
Note that if you don't need to keep the data structure intact (containing only the displayed values), a common solution is to use dictionaries.
You could use common dictionary that has the role as key and the data structure as value:
class TableModel(QAbstractTableModel):
def __init__(self, data):
super().__init__()
rows = len(data)
cols = len(data[0])
self._data = {
Qt.DisplayRole: data,
Qt.BackgroundRole: [[None] * cols for _ in range(rows)]
}
# implement the other functions accordingly
Otherwise, use a single structure that uses unique dictionaries for each item:
class TableModel(QAbstractTableModel):
def __init__(self, data):
super().__init__()
self._data = []
for rowData in data:
self._data.append([
{Qt.DisplayRole: item} for item in rowData
])
def data(self, index, role=Qt.DisplayRole):
if not index.isValid():
return
data = self._data[index.row()][index.column()]
if role == Qt.EditRole:
role = Qt.DisplayRole
return data.get(role)
def setData(self, index, value, role=Qt.EditRole):
if (
not index.isValid()
or role not in (Qt.EditRole, Qt.BackgroundRole)
):
return False
self._data[index.row()][index.column()][role] = value
self.dataChanged.emit(index, index, [role])
return True

Related

PyQt6 How to get Tableview header name/text from item on click

I've got a gui app in PyQt6 that just has a button and table view in it. Once pressed, the button connects TableModel, which inherits from QtCore.QAbstractTableModel, to the table view populates the data a does a bit of formatting. Great.
What I now want is to be able to access the header names (just the text thats in the headers), when a cell in the table is clicked. I've successfully connected a function that just prints out item.row() and item.column() and this is functioning correctly. I can't for the life of me get the header info though. Any help would be great
Code so far
I'm just posting the most relevant parts of the code, as it's long and spread over multiple files. Just lmk if there's more you need to see.
class PrimaryWindow(QtWidgets.QMainWindow):
"""docstring for PrimaryWindow"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.dbloc=r'test.sqlite'
self.conn=sqlite3.connect(self.dbloc)
#do all the connections
self.ui.DataButton.clicked.connect(self.get_data)
self.ui.DataTable.clicked.connect(self.Get_new_view)
def get_data(self):
#get some data from db
self.tmodel = TableModel(self.data)
self.ui.DataTable.setModel(self.tmodel)
def Get_new_view(self, item):
print('clicked',item.row(),item.column())
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, data):
super(TableModel, self).__init__()
self._data = data
def data(self, index, role):
if role == Qt.ItemDataRole.BackgroundRole:
colors={
20:'#da172e', #red
15:'#ede60b', #yellow
10:'#0bed10', #green
99:'#0b6ded', #blue
5: '#FFFFFF' #white
}
value = self._data.iloc[index.row(),index.column()]
if value == 0:
return #don't color 0 values
else:
return QtGui.QColor(colors[max(i for i in colors if i<=value)]) #returns threshold value as key to color dict, sends string of hex color code
if role == Qt.ItemDataRole.DisplayRole:
# See below for the nested-list data structure.
# .row() indexes into the outer list,
# .column() indexes into the sub-list
return str(self._data.iloc[index.row(),index.column()])
def rowCount(self, index):
# The length of the outer list.
return len(self._data)
def columnCount(self, index):
# The following takes the first sub-list, and returns
# the length (only works if all rows are an equal length
return len(self._data.columns)
def headerData(self, section, orientation, role):
# section is the index of the column/row.
if role == Qt.ItemDataRole.DisplayRole:
if orientation == Qt.Orientation.Horizontal:
return str(self._data.columns[section])
if orientation == Qt.Orientation.Vertical:
return str(self._data.index[section])
def flags(self, index):
return Qt.ItemFlag.ItemIsSelectable|Qt.ItemFlag.ItemIsEnabled|Qt.ItemFlag.ItemIsEditable

How to SetData in a QtableView Cell using pyside

I'm trying to set a value in a cell in my QtableView. I'm using Pyside2.
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, mlist=None):
super(TableModel, self).__init__()
self._items = [] if mlist == None else mlist
self._header = []
def data(self, index, role = QtCore.Qt.DisplayRole):
if not index.isValid():
return None
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
return self._items[index.row()][index.column()]
return None
def setData(self, index, value, role = QtCore.Qt.EditRole):
if value is not None and role == QtCore.Qt.EditRole:
self._items[index.row()][index.column()] = value
return True
return False
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
# skip the irrelevant code #
Table = QTableView()
model = TableModel()
Table.setModel(model)
row, column = a_function_that_outputs_the_row_and_column_of_the_cell_to_edit()
self.Table.model().setData(index ?, value)
What I'm struggling with is getting to understand how to pass the index as an argument, I have the row and column, any help on how to do that properly?
You need to use model.index(row, column, parent=None) (see the documentation) to get the appropriate QModelIndex.
If the model is two dimensional (not a tree view), the parent is not required:
model.setData(model.index(row, column), value)

How to undo a change in QAbstractTableModel?

I have this simple example: a value in last column of my QAbstractTableModel equals value in column 1 multiplied by 2. So every time a change is made to value in column 1 - it results to a change in column 2.
When the value in the last column has changed - a message box is shown asking whether user wishes confirm action.
Imagine user have changed value in column 1 and sees this message: I wish my app to undo changes if cancel is clicked (return both old values in column 1 and 2), can you help me with that? I need to define my 'go_back()' function:
class Mainwindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.table = QtWidgets.QTableView()
self.setCentralWidget(self.table)
self.data = [
[1, 0.18, 0.36],
[2, 0.25, 0.50],
[3, 0.43, 0.86],
]
self.model = MyModel(self.data)
self.table.setModel(self.model)
self.table.setSelectionBehavior(self.table.SelectRows)
self.table.setSelectionMode(self.table.SingleSelection)
self.model.dataChanged.connect(lambda index: self.count_last_column(index))
self.model.dataChanged.connect(lambda index: self.if_last_column_changed(index))
def calculations(self, position):
value = self.model.list_data[position][1] * 2
return value
def count_last_column(self, index):
if index.column() == 1:
position = index.row()
self.model.setData(self.model.index(position,2), self.calculations(position))
def if_last_column_changed(self, index):
if index.column() == 2:
message_box, message_box_button = self.show_message_box()
if message_box_button == 'Ok':
pass
elif message_box_button == 'Cancel':
self.go_back()
def show_message_box(self):
self.message_box = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, 'Action', 'Value in column 3 has changed, confirm action?')
self.message_box.Ok = self.message_box.addButton(QtWidgets.QMessageBox.Ok)
self.message_box.Cancel = self.message_box.addButton(QtWidgets.QMessageBox.Cancel)
self.message_box.exec()
if self.message_box.clickedButton() == self.message_box.Ok:
return (self.message_box, 'Ok')
elif self.message_box.clickedButton() == self.message_box.Cancel:
return (self.message_box, 'Cancel')
def go_back(self):
pass #################
class MyModel(QtCore.QAbstractTableModel):
def __init__(self, list_data = [[]], parent = None):
super(MyModel, self).__init__()
self.list_data = list_data
def rowCount(self, parent):
return len(self.list_data)
def columnCount(self, parent):
return len(self.list_data[0])
def data(self, index, role):
if role == QtCore.Qt.DisplayRole:
row = index.row()
column = index.column()
value = self.list_data[row][column]
return value
if role == QtCore.Qt.EditRole:
row = index.row()
column = index.column()
value = self.list_data[row][column]
return value
def setData(self, index, value, role = QtCore.Qt.EditRole):
if role == QtCore.Qt.EditRole:
row = index.row()
column = index.column()
self.list_data[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 | QtCore.Qt.ItemIsUserCheckable
if __name__ == '__main__':
app = QtWidgets.QApplication([])
application = Mainwindow()
application.show()
sys.exit(app.exec())
One option is to use a QUndoStack with the item model, and push QUndoCommand objects onto the stack in setData. The benefit of this approach is that it makes it simple to implement more undo/redo controls going forward, if you want to.
In MyModel, just create a stack in the constructor and add a line to push a command onto the stack right before you modify the list data (so the previous value can be stored in the command). The rest of the class is unchanged.
class MyModel(QtCore.QAbstractTableModel):
def __init__(self, list_data = [[]], parent = None):
super(MyModel, self).__init__()
self.list_data = list_data
self.stack = QtWidgets.QUndoStack()
def setData(self, index, value, role = QtCore.Qt.EditRole):
if role == QtCore.Qt.EditRole:
row = index.row()
column = index.column()
self.stack.push(CellEdit(index, value, self))
self.list_data[row][column] = value
self.dataChanged.emit(index, index)
return True
return False
Create the QUndoCommand with the index, value, and model passed to the constructor so the desired cell can be modified with calls to undo or redo.
class CellEdit(QtWidgets.QUndoCommand):
def __init__(self, index, value, model, *args, **kwargs):
super().__init__(*args, **kwargs)
self.index = index
self.value = value
self.prev = model.list_data[index.row()][index.column()]
self.model = model
def undo(self):
self.model.list_data[self.index.row()][self.index.column()] = self.prev
def redo(self):
self.model.list_data[self.index.row()][self.index.column()] = self.value
And now all that needs to be done in go_back is to call the undo method twice, for both cells that were modified.
def go_back(self):
self.model.stack.undo()
self.model.stack.undo()

How to lazy load changing data into a QColumnView (with PyQt)?

I have a hierarchical data source for a QColumnView I want to fill. The data source loads the data from a server using a REST interface.
Lets say the hierarchy looks like this:
Car_Manufacturer -> Car_Type -> Specific_Model -> Motor_Type
I have to use a QColumnView to display this (since it is a customer requirement). The behavior is supposed to be like this:
When the program starts, it loads the Car_Manufacturer from the server. When one of the Car_Manufacturer items is clicked, the Car_Type items for the selected Car_Manufacturer is loaded from the server and displayed in a new column. When the Car_Manufacturer is clicked again, the data has to be fetched again from the server and the column has to be updated. When Car_Type is clicked, the Specific_Model items for this Car_Manufacturer and Car_type have to be queried from the server and loaded into a new column... and so on.
The datasource has this api:
datasource.get_manufacturers(hierarchy) # hierarchy = []
datasource.get_car_type(hierarchy) # hierarchy = [manufacturer, ]
datasource.get_specific_model(hierarchy) # hierarchy = [manufacturer, car_type]
datasource.get_motor_type(hierarchy) # hierarchy = [manufacturer, car_type, specific_model ]
Where each element in the hierarchy is a string key representation of the item. When an item is clicked it has to inform a controller about this with the hierarchy of the curernt item.
How can I get the QColumnView to update the children of one item when the item is clicked using the datasource? How can this stay flexible when a new hierarchy layer is added or removed?
Here is an example which implements a custom DirModel.
The method _create_children is called lazily and should return a list of instances which implement AbstractTreeItem.
import sys
import os
import abc
from PyQt4.QtCore import QAbstractItemModel, QModelIndex, Qt, QVariant
from PyQt4.QtGui import QColumnView, QApplication
class TreeModel(QAbstractItemModel):
def __init__(self, root, parent=None):
super(TreeModel, self).__init__(parent)
self._root_item = root
self._header = self._root_item.header()
def columnCount(self, parent=None):
if parent and parent.isValid():
return parent.internalPointer().column_count()
else:
return len(self._header)
def data(self, index, role):
if not index.isValid():
return QVariant()
item = index.internalPointer()
if role == Qt.DisplayRole:
return item.data(index.column())
if role == Qt.UserRole:
if item:
return item.person
return QVariant()
def headerData(self, column, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
try:
return QVariant(self._header[column])
except IndexError:
pass
return QVariant()
def index(self, row, column, parent):
if not self.hasIndex(row, column, parent):
return QModelIndex()
if not parent.isValid():
parent_item = self._root_item
else:
parent_item = parent.internalPointer()
child_item = parent_item.child_at(row)
if child_item:
return self.createIndex(row, column, child_item)
else:
return QModelIndex()
def parent(self, index):
if not index.isValid():
return QModelIndex()
child_item = index.internalPointer()
if not child_item:
return QModelIndex()
parent_item = child_item.parent()
if parent_item == self._root_item:
return QModelIndex()
return self.createIndex(parent_item.row(), 0, parent_item)
def rowCount(self, parent=QModelIndex()):
if parent.column() > 0:
return 0
if not parent.isValid():
parent_item = self._root_item
else:
parent_item = parent.internalPointer()
return parent_item.child_count()
class AbstractTreeItem(object):
__metaclass__ = abc.ABCMeta
def __init__(self, parent=None):
self._children = None
self._parent = parent
#abc.abstractmethod
def header(self):
#return ["name"]
raise NotImplementedError(self.header)
#abc.abstractmethod
def column_count(self):
#return 1
raise NotImplementedError(self.column_count)
def parent(self):
return self._parent
#abc.abstractmethod
def _create_children(self):
# subclass this method
return []
def row(self):
if self._parent:
return self._parent._children.index(self)
return 0
#property
def children(self):
if self._children is None:
self._children = self._create_children()
return self._children
def child_at(self, row):
return self.children[row]
#abc.abstractmethod
def data(self, column):
#return ""
raise NotImplementedError(self.data)
def child_count(self):
count = len(self.children)
return count
class DirPathModel(AbstractTreeItem):
def __init__(self, root="/", parent=None):
super(DirPathModel, self).__init__(parent)
self._root = root
def _create_children(self):
print "walking into", self._root
children = []
try:
entries = os.listdir(self._root)
except OSError:
# no permission etc
entries = []
for name in entries:
fn = os.path.join(self._root, name)
if os.path.isdir(fn):
children.append(self.__class__(fn, self))
return children
def data(self, column):
#assert column == 0
return os.path.basename(self._root)
def header(self):
return ["name"]
def column_count(self):
return 1
def main():
app = QApplication(sys.argv)
view = QColumnView()
view.setWindowTitle("Dynamic Column view test")
view.resize(1024, 768)
root = DirPathModel("/")
model = TreeModel(root)
view.setModel(model)
view.show()
return app.exec_()
if __name__ == "__main__":
sys.exit(main() or 0)
Asuming you can't bring all data at once and filter it out, you'll have to modify the item model (adding and removing rows) on the go based on whatever the user has selected from the QColumnView.
There's more than one way to remove the items:
You can use the index of the selected column and remove all items "on the left" of this column.
You can remove items based whose parent (or grandparent) matches the selection being made
Any option you take, you'll have to mirror the relationship between items in some way. That or implement from QAbstractItemModel, which I think would be an overkill.

PySide - Updating data in QAbstractTableModel

I have a question since I read a lot of tutorial but can't figured how to make my program work properly.
I want to subclass QAbtractTableModel and set this model to a QTableView. Then I want to change some items in the view. I've create a simple program to experiment but I can't manage to get it work without creating a new model and set the new model each time.
What I ask is: can I change the items of the model and then automatically update the view ? I know it is possible with dataChanged() but I don't understand how it works.
The perfect solution would be to "bind" a variable (list1) with the data of the table model and any time the variable is modify the model and the view are updated. But I don't know if it is possible.
I read a lot about signals/slots, delegates, model/view and I'm lost.
class MyTableModel(QtCore.QAbstractTableModel):
def __init__(self, symbList=[[]], parent=None):
QtCore.QAbstractTableModel.__init__(self, parent)
self.header = ['Char', 'Dec', 'Hex']
self.symbList = symbList
def rowCount(self, parent):
return len(self.symbList)
def columnCount(self, parent):
if len(self.symbList) > 0:
return len(self.symbList[0])
return 0
def data(self, index, role):
if not index.isValid():
return None
elif role != QtCore.Qt.DisplayRole:
return None
return self.symbList[index.row()][index.column()]
"""
def flags(self, index):
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable
def setData(self, index, value, role=QtCore.Qt.EditRole):
self.symbList[index.row()][index.column()] = value
self.dataChanged.emit(index, index)
return True
"""
def headerData(self, col, orientation, role):
if orientation == QtCore.Qt.Horizontal and \
role == QtCore.Qt.DisplayRole:
return self.header[col]
return None
def sort(self, col, order):
"""sort table by given column number col"""
self.layoutAboutToBeChanged.emit()
self.symbList = sorted(self.symbList,
key=operator.itemgetter(col))
if order == QtCore.Qt.DescendingOrder:
self.symbList.reverse()
self.layoutChanged.emit()
if __name__ == '__main__':
list1 = [['Z', '90', '5A'], ['R', '82', '52']]
list2 = [['G', '71', '47'], ['O', '79', '4F']]
app = QtGui.QApplication([])
table = QtGui.QTableView() # the view
table.show()
tableModel = MyTableModel(list1) # create a model with list1
table.setModel(tableModel)
tableModel = MyTableModel(list2) # override the table with list2
table.setModel(tableModel)
sys.exit(app.exec_())

Categories

Resources