PyQt5 update values in editable QTableView - python

I have an editable QTableView with a range of x values, their squares and their cubes.
Is there a way that if any value is changed a signal is launched to update the rest of the cells in the same row?
For instance, if I change the value x = 2 by x = 5, then somehow to know that the change has happened and the code has to update the rest of the values in the row.
I paste in a sample of my original code in case it helps.
from PyQt5.QtCore import QAbstractTableModel, Qt
class PandasModelEditable(QAbstractTableModel):
def __init__(self, data):
QAbstractTableModel.__init__(self)
self._data = data
def rowCount(self, parent=None):
return self._data.shape[0]
def columnCount(self, parnet=None):
return self._data.shape[1]
def data(self, index, role=Qt.DisplayRole):
if index.isValid():
if role == Qt.DisplayRole:
return str(self._data.iloc[index.row(), index.column()])
column_count = self.columnCount()
for column in range(0, column_count):
if (index.column() == column and role == Qt.TextAlignmentRole):
return Qt.AlignHCenter | Qt.AlignVCenter
return None
def headerData(self, col, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self._data.columns[col]
return None
def setData(self, index, value, role):
if not index.isValid():
return False
if role != Qt.EditRole:
return False
row = index.row()
if row < 0 or row >= len(self._data.values):
return False
column = index.column()
if column < 0 or column >= self._data.columns.size:
return False
self._data.values[row][column] = value
self.dataChanged.emit(index, index)
return True
def flags(self, index):
return Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable
if __name__ == '__main__':
import sys
import pandas as pd
from PyQt5.QtWidgets import QApplication, QTableView
df = pd.DataFrame({'x': range(5),
'x²': [i**2 for i in range(5)],
'x³': [i**3 for i in range(5)]
})
app = QApplication(sys.argv)
model = PandasModelEditable(df)
view = QTableView()
view.setModel(model)
view.resize(350, 200)
view.show()
sys.exit(app.exec_())
EDITED
Since the kind answers are not 100 % helpful and I populate the QtableView with a pandas DataFrame, I have opened a new post with a new question.

I noted for you the lines in which I made changes.
from PyQt5.QtCore import QAbstractTableModel, Qt
class PandasModelEditable(QAbstractTableModel):
def __init__(self, data):
QAbstractTableModel.__init__(self)
self._data = data
def rowCount(self, parent=None):
return self._data.shape[0]
def columnCount(self, parnet=None):
return self._data.shape[1]
def data(self, index, role=Qt.DisplayRole):
if index.isValid():
if role == Qt.DisplayRole:
return str(self._data.iloc[index.row(), index.column()])
column_count = self.columnCount()
for column in range(0, column_count):
if (index.column() == column and role == Qt.TextAlignmentRole):
return Qt.AlignHCenter | Qt.AlignVCenter
return None
def headerData(self, col, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self._data.columns[col]
return None
def setData(self, index, value, role):
if not value.isdigit(): # +++
return False # +++
if not index.isValid():
return False
if role != Qt.EditRole:
return False
row = index.row()
if row < 0 or row >= len(self._data.values):
return False
column = index.column()
if column < 0 or column >= self._data.columns.size:
return False
self._data.values[row][column] = value
self._data.values[row][1] = int(value)**2 # +++
self._data.values[row][2] = int(value)**3 # +++
self.dataChanged.emit(index, index)
return True
def flags(self, index):
# return Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable
fl = QAbstractTableModel.flags(self, index) # +++
if index.column() == 0: # +++
fl |= Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable # +++
return fl # +++
if __name__ == '__main__':
import sys
import pandas as pd
from PyQt5.QtWidgets import QApplication, QTableView
df = pd.DataFrame({'x': range(5),
'x²': [i**2 for i in range(5)],
'x³': [i**3 for i in range(5)]
})
app = QApplication(sys.argv)
model = PandasModelEditable(df)
view = QTableView()
view.setModel(model)
view.resize(350, 200)
view.show()
sys.exit(app.exec_())

Related

Filter data from dataChanged signal in PyQt5

I wish to filter change made to QModelIndex at specific column (for example column 1), and that a change was made to CheckStateRole, not to DisplayRole. I need to filter just the fact that CheckStateRole was changed (ignoring which value it has now). Is it possible?
self.model.dataChanged.connect(lambda x: self.foo(x))
def foo(self, x):
if x.column() == 1 and ???????:
...
I tried x.data(QtCore.Qt.CheckStateRole) == 0, but that's not what I need
here's an example of a code to test:
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
class Mainwindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.table = QtWidgets.QTableView()
self.setCentralWidget(self.table)
self.data = [
['id_1', 'Blocks γ=500 GOST 31359-2007', 0.18, 0.22],
['id_2', 'Blocks γ=600 GOST 31359-2008', 0.25, 0.27],
['id_3', 'Insulation', 0.041, 0.042],
['id_4', 'Insulation', 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 self.model.materials:
key = row[0]
self.model.check_states[key] = 0
self.model.dataChanged.connect(lambda: print(self.model.materials))
self.model.dataChanged.connect(lambda: print(self.model.check_states))
self.model.dataChanged.connect(lambda x: self.foo(x)) ######################
def foo(self, x):
if x.column() == 1 #and ???????????????:
print('success')
class Materials(QtCore.QAbstractTableModel):
def __init__(self, materials = [[]], parent = None):
super(Materials, self).__init__()
self.materials = materials
self.check_states = {}
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.CheckStateRole:
if index.column() == 1:
row = index.row()
value = self.check_states.get(self.materials[row][0])
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)
return True
if role == QtCore.Qt.CheckStateRole:
if index.column() == 1:
row = index.row()
self.check_states[self.materials[row][0]] = 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())
The aim is to print 'success' not only when a change was in column 1, but when user changes checkbox status.

Change state of checkbox programmatically in qtableview

I found this model to visualize qtableview with checkboxes. It works, but now I want also to change the state of checkboxes programmatically (for example a button that check/uncheck all checkboxes). I have no idea how I can do it...
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class TableModel(QAbstractTableModel):
def __init__(self, parent=None):
super(TableModel, self).__init__(parent)
self.tableData = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
self.checks = {}
def columnCount(self, *args):
return 3
def rowCount(self, *args):
return 3
def checkState(self, index):
if index in self.checks.keys():
return self.checks[index]
else:
return Qt.Unchecked
def data(self, index, role=Qt.DisplayRole):
row = index.row()
col = index.column()
if role == Qt.DisplayRole:
return '{0}'.format(self.tableData[row][col])
elif role == Qt.CheckStateRole and col == 0:
return self.checkState(QPersistentModelIndex(index))
return None
def setData(self, index, value, role=Qt.EditRole):
if not index.isValid():
return False
if role == Qt.CheckStateRole:
self.checks[QPersistentModelIndex(index)] = value
return True
return False
def flags(self, index):
fl = QAbstractTableModel.flags(self, index)
if index.column() == 0:
fl |= Qt.ItemIsEditable | Qt.ItemIsUserCheckable
return fl
You have to use the setData() method, in this method the dataChanged signal must be emitted when the value associated with a role changes:
def setData(self, index, value, role=Qt.EditRole):
if not index.isValid():
return False
if role == Qt.CheckStateRole:
self.checks[QPersistentModelIndex(index)] = value
self.dataChanged.emit(index, index)
return True
return False
If you want to check and uncheck the items you must iterate over the items:
class Widget(QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
self.button = QPushButton("Checked", checkable=True)
self.button.clicked.connect(self.on_clicked)
self.view = QTableView()
self.model = TableModel(self)
self.view.setModel(self.model)
lay = QVBoxLayout(self)
lay.addWidget(self.button)
lay.addWidget(self.view)
#pyqtSlot(bool)
def on_clicked(self, state):
c = 0
for r in range(self.model.rowCount()):
ix = self.model.index(r, c)
self.model.setData(
ix, Qt.Checked if state else Qt.Unchecked, Qt.CheckStateRole
)
self.button.setText("Unchecked" if state else "Checked")

Remove QComboBox when QCheckBox is toggled off or on using QItemDelegate

I would like to update the cell content of a QTableView with a ComboBox whenever the toggle of a Checkbox above changes. I am using QTableView and a custom delegate to draw the ComboBoxes. The Checkboxes are controlled within the QTableView itself. Currently, when I toggle the checkboxes, the Comboboxes below will appear, but I could not manage to remove the ComboBoxes when toggling off the CheckBoxes.
My code sample is below.
import sys
import pandas as pd
from pandas.api.types import is_numeric_dtype
import numpy as np
from PyQt5.QtCore import (QAbstractTableModel, Qt, pyqtProperty, pyqtSlot,
QVariant, QModelIndex, pyqtSignal)
from PyQt5.QtWidgets import (QComboBox, QApplication, QAbstractItemView,
QItemDelegate, QCheckBox, QMainWindow, QTableView)
class DataFrameModel(QAbstractTableModel):
DtypeRole = Qt.UserRole + 1000
ValueRole = Qt.UserRole + 1001
def __init__(self, df=pd.DataFrame(), parent=None):
super(DataFrameModel, self).__init__(parent)
self._dataframe = df
self.df2 = pd.DataFrame(self._dataframe.iloc[2:3, :].to_dict())
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, 1]:
pass
else:
return self._dataframe.index.tolist()[section - 2]
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():
return None
col = index.column()
row = index.row()
dt = self.df2[self.df2.columns[col]].dtype
is_numeric = is_numeric_dtype(self.df2[self.df2.columns[col]])
if row == 0 and is_numeric:
value = self._dataframe.iloc[row, col].text()
else:
value = self._dataframe.iloc[row, col]
if role == Qt.DisplayRole:
return value
elif role == Qt.CheckStateRole:
if row == 0 and is_numeric:
if self._dataframe.iloc[row, col].isChecked():
return Qt.Checked
else:
return Qt.Unchecked
elif role == DataFrameModel.ValueRole:
return value
elif role == DataFrameModel.ValueRole:
return value
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=Qt.EditRole):
if not index.isValid():
return False
col = index.column()
row = index.row()
is_numeric = is_numeric_dtype(self.df2[self.df2.columns[col]])
if role == Qt.CheckStateRole and index.row() == 0:
if is_numeric:
if value == Qt.Checked:
self._dataframe.iloc[row, col].setChecked(True)
self._dataframe.iloc[row, col].setText("Grade Item")
else:
self._dataframe.iloc[row, col].setChecked(False)
self._dataframe.iloc[row, col].setText("Not a Grade")
elif row == 1 and role == Qt.EditRole:
if isinstance(value, QVariant):
value = value.value()
if hasattr(value, 'toPyObject'):
value = value.toPyObject()
self._dataframe.iloc[row, col] = value
elif row >= 2 and role == Qt.EditRole:
try:
value = eval(value)
if not isinstance(
value,
self._dataframe.applymap(type).iloc[row, col]):
value = self._dataframe.iloc[row, col]
except:
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):
if not index.isValid():
return None
if index.row() == 0:
return (Qt.ItemIsEnabled | Qt.ItemIsSelectable |
Qt.ItemIsUserCheckable)
else:
return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable
def sort(self, column, order):
self.layoutAboutToBeChanged.emit()
col_name = self._dataframe.columns.tolist()[column]
sheet1 = self._dataframe.iloc[:2, :]
sheet2 = self._dataframe.iloc[2:, :].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, parent, choices=None):
super().__init__(parent)
self.items = choices
def createEditor(self, parent, option, index):
self.parent().model().dataChanged.emit(index, index, (Qt.DisplayRole,))
if is_numeric_dtype(
self.parent().model().df2[
self.parent().model().df2.columns[index.column()]]):
checked = self.parent().model().dataFrame.iloc[
0, index.column()].isChecked()
if checked:
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):
editor = self.sender()
self.commitData.emit(editor)
class MainWindow(QMainWindow):
def __init__(self, pandas_sheet):
super().__init__()
self.pandas_sheet = pandas_sheet
self.table = QTableView()
self.setCentralWidget(self.table)
check_bx_lst = []
is_number = [is_numeric_dtype(self.pandas_sheet[col]) for col
in self.pandas_sheet.columns]
for is_numb in is_number:
if is_numb:
checkbox = QCheckBox('Not a Grade')
checkbox.setChecked(False)
check_bx_lst.append(checkbox)
else:
check_bx_lst.append(None)
for i in range(2):
self.pandas_sheet.loc[-1] = [' '] * \
self.pandas_sheet.columns.size
self.pandas_sheet.index = self.pandas_sheet.index + 1
self.pandas_sheet = self.pandas_sheet.sort_index()
self.pandas_sheet.loc[0] = check_bx_lst
model = DataFrameModel(self.pandas_sheet)
self.table.setModel(model)
self.table.setSortingEnabled(True)
delegate = ComboBoxDelegate(self.table,
[None, 'Test', 'Quiz'])
self.table.setItemDelegateForRow(1, delegate)
self.table.resizeColumnsToContents()
self.table.resizeRowsToContents()
if __name__ == '__main__':
df = pd.DataFrame({'a': ['student ' + str(i) for i in range(5)],
'b': np.arange(5),
'c': np.random.rand(5)})
app = QApplication(sys.argv)
window = MainWindow(df)
window.table.model().sort(df.columns.get_loc("a"), Qt.AscendingOrder)
window.setFixedSize(280, 200)
window.show()
sys.exit(app.exec_())
I would like to remove the Combobox when the checkbox above is toggled off.
Any help is really appreciated.
You are using openPersistentEditor within the paint function, which is simply wrong: painting happens very often for every index the delegate is used, and you're practically calling createEditor each time each cell in that row is painted, something that happens for all the cells when the view is scrolled, or for any cell hovered by the mouse.
Following your logic, the creator is finally created probably due to painting requested by data change, because at that point the if conditions in createEditor are True. From that point on, you create a persistent editor, and if you don't remove it it will just stay there.
Obviously, all this is not a good approach, mostly because you virtually check if it's ok to create the editor from a paint function, which doesn't make much sense.
You should connect to the dataChanged signal for the model to verify the checked status and then open or close the editor accordingly.
class MainWindow(QMainWindow):
def __init__(self, pandas_sheet):
# ...
model.dataChanged.connect(self.dataChanged)
def dataChanged(self, topLeft, bottomRight, roles):
if topLeft.row() == 0:
if topLeft.data(QtCore.Qt.CheckStateRole):
self.table.openPersistentEditor(topLeft.sibling(1, topLeft.column()))
else:
self.table.closePersistentEditor(topLeft.sibling(1, topLeft.column()))
I've over-simplified the if condition, but I assume that the concept is clear enough.

QColorDialog and QItemDelegate

I have a QTableView and I'm Using a QItemDelegate in it as button.
I'm trying to change the color of the button, so when i click on it i call a QColorDialog. But then I'm having trouble sending the color it back to the button.
Here's how it is going so far:
the Button and QColorDialog:
class ButtonDelegate(QItemDelegate):
def __init__(self, parent):
QItemDelegate.__init__(self, parent)
def paint(self, painter, option, index):
widget = QWidget()
layout = QHBoxLayout()
widget.setLayout(layout)
btn = QPushButton('')
btn.setStyleSheet("background-color:rgb(86,12,65)")
ix = QPersistentModelIndex(index)
btn.clicked.connect(lambda ix = ix : self.onClicked(ix))
layout.addWidget(btn)
layout.setContentsMargins(2,2,2,2)
if not self.parent().indexWidget(index):
self.parent().setIndexWidget(index, widget)
def onClicked(self, ix):
colorPicker = QColorDialog.getColor()
#colorPicker.show()
r = str(colorPicker.red())
g = str(colorPicker.red())
b = str(colorPicker.red())
bgcolor = 'background-color:rgb(' + r + ',' + g + ',' + b +')'
What's the next step? I tried declaring the button in the delegate init as self.btn = QPushButton() and then reuse it at the onCLick Method, but the button don't even get drawn that way.
Some enlightenment?
Thank you!
edit 1
Model:
class Model(QAbstractTableModel):
def __init__(self, vtxTable, parent = None):
QAbstractTableModel.__init__(self, parent)
#data
self.groups = []
#header
self.header_labels = ['Color', 'Group', 'Done']
self.vtxTable = vtxTable
def rowCount(self, parent):
return len(self.groups)
def columnCount(self, parent):
return 3
def flags(self, index):
if index.column() == 2:
fl = fl = Qt.ItemIsEnabled | Qt.ItemIsSelectable
else:
fl = Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsEditable
return fl
def headerData(self, section, orientation, role):
if role == Qt.DisplayRole and orientation == Qt.Horizontal:
return self.header_labels[section]
def removeRow(self, row, parent = QModelIndex()):
self.beginRemoveRows(parent, row, row)
self.groups.remove(self.groups[row])
self.endRemoveRows()
self.vtxTable.setModel(QStringListModel())
def insertRows(self, position, row, values = [] , parent = QModelIndex()):
lastposition = self.rowCount(0)
self.beginInsertRows(parent, lastposition, lastposition)
self.groups.insert(lastposition, values)
self.endInsertRows()
def setData(self, index, value, role = Qt.EditRole):
setIt = False
value = value
row = index.row()
column = index.column()
if role == Qt.EditRole:
setIt = True
if not len(value) == 0:
if value in self.getGrpNames():
warning("Group must have a unique name.")
setIt = False
else:
setIt = True
else:
warning("New group must have a name.")
setIt = False
if role == Qt.BackgroundRole:
setIt = True
if setIt:
self.groups[row][column] = value
self.dataChanged.emit(row, column)
return False
def data(self, index, role):
if not index.isValid():
return
row = index.row()
column = index.column()
if role == Qt.DisplayRole:
if column == 0:
#value = [self.groups[row][column].redF(), self.groups[row][column].greenF(), self.groups[row][column].blueF()]
value = self.groups[row][column]
else:
value = self.groups[row][column]
return value
elif role == Qt.TextAlignmentRole:
return Qt.AlignCenter;
elif role == Qt.EditRole:
index = index
return index.data()
elif role == Qt.BackgroundRole and column == 0:
value = self.groups[row][column]
def getGrpNames(self):
rows = self.rowCount(1)
grps = []
for row in range(rows):
grp = self.index(row, 1).data()
grps.append(grp)
return grps
def getAllVtx(self):
rows = self.rowCount(1)
allVtxs = []
for row in range(rows):
index = self.createIndex(row, 3)
vtxs = index.data()
for vtx in vtxs:
allVtxs.append(vtx)
return allVtxs
def getData(self):
rows = self.rowCount(1)
data = {}
for row in range(rows):
color = self.index(row, 0).data()
grp = self.index(row, 1).data()
done = self.index(row, 2).data()
vtxs = self.groups[row][3]
#index = self.createIndex(row,0)
data[grp] = [grp, color, done, vtxs]
return data
def queryVtx(self, vtx):
data = self.getData()
for key in data:
vtxs = data[key][3]
if vtx in vtxs:
return data[key][0]
else:
return False
Table View:
class Table(QTableView):
def __init__(self, *args, **kwargs):
QTableView.__init__(self, *args, **kwargs)
self.setItemDelegateForColumn(0, colorDelegate(self))
hHeader = self.horizontalHeader()
#hHeader.setSectionResizeMode(QHeaderView.Fixed);
self.setSelectionBehavior(QAbstractItemView.SelectRows)
self.setSelectionMode(QAbstractItemView.SingleSelection)
vHeader = self.verticalHeader()
vHeader.hide()
When clicking on the first cell of the row I'd like to be able top pick a color for it, and save it in the model.
Thank you.
The goal of the delegates is to customize each item that is displayed in a QAbstractItemView, the other way to do it is by inserting a widget using the indexWidget method. The advantage of the delegates is that the memory consumption is minimal. It is advisable not to use them at the same time.
The delegates have the following methods:
paint(): is the method responsible for drawing the item that is normally displayed
createEditor(): is the method is responsible for creating the editor.
setEditorData(): get the value of the model and establish it in the editor.
setModelData(): save the data obtained from the editor to the model.
An example of that type of delegate is the following:
from PySide2.QtWidgets import *
from PySide2.QtGui import *
from PySide2.QtCore import *
class Delegate(QStyledItemDelegate):
def createEditor(self, parent, option, index):
dialog = QColorDialog(parent)
return dialog
def setEditorData(self, editor, index):
color = index.data(Qt.BackgroundRole)
editor.setCurrentColor(color)
def setModelData(self, editor, model, index):
color = editor.currentColor()
model.setData(index, color, Qt.BackgroundRole)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
model = QStandardItemModel(4, 4)
for i in range(model.rowCount()):
for j in range(model.columnCount()):
color = QColor(qrand() % 256, qrand() % 256, qrand() % 256)
it = QStandardItem("{}{}".format(i, j))
it.setData(color, Qt.BackgroundRole)
model.setItem(i, j, it)
w = QTableView()
w.setModel(model)
w.setItemDelegate(Delegate())
w.show()
sys.exit(app.exec_())
Update:
I have improved your code since it had unnecessary elements, the main error is that these Qt::BackgroundRole must return a QColor
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
import warnings
class Model(QAbstractTableModel):
def __init__(self, parent = None):
QAbstractTableModel.__init__(self, parent)
#data
self.groups = []
#header
self.header_labels = ['Color', 'Group', 'Done']
def rowCount(self, parent=QModelIndex()):
return len(self.groups)
def columnCount(self, parent=QModelIndex()):
return 3
def flags(self, index):
fl = Qt.ItemIsEnabled | Qt.ItemIsSelectable
if not index.column() in (2, ):
fl |= Qt.ItemIsEditable
return fl
def headerData(self, section, orientation, role):
if role == Qt.DisplayRole and orientation == Qt.Horizontal:
return self.header_labels[section]
def removeRow(self, row, parent = QModelIndex()):
self.beginRemoveRows(parent, row, row)
self.groups.remove(self.groups[row])
self.endRemoveRows()
def insertRows(self, values = [], position=-1):
if position == -1:
position = self.rowCount()
self.beginInsertRows(QModelIndex(), position, position)
self.groups.insert(position, values)
self.endInsertRows()
def setData(self, index, value, role = Qt.EditRole):
setIt = False
row = index.row()
column = index.column()
if role == Qt.EditRole:
setIt = True
if len(value) != 0:
if value in self.getGrpNames():
warning("Group must have a unique name.")
setIt = False
else:
setIt = True
else:
warning("New group must have a name.")
setIt = False
if role == Qt.BackgroundRole:
setIt = True
if setIt:
self.groups[row][column] = value
self.dataChanged.emit(index, index)
return False
def data(self, index, role):
if not index.isValid():
return
row = index.row()
column = index.column()
value = None
if role == Qt.DisplayRole:
if column == 0:
value = self.groups[row][column]
else:
value = self.groups[row][column]
elif role == Qt.TextAlignmentRole:
value = Qt.AlignCenter;
elif role == Qt.BackgroundRole and column == 0:
value = QColor(self.groups[row][column])
return value
def getGrpNames(self):
rows = self.rowCount(1)
grps = []
for row in range(rows):
grp = self.index(row, 1).data()
grps.append(grp)
return grps
def getAllVtx(self):
rows = self.rowCount(1)
allVtxs = []
for row in range(rows):
index = self.createIndex(row, 3)
vtxs = index.data()
for vtx in vtxs:
allVtxs.append(vtx)
return allVtxs
def getData(self):
rows = self.rowCount(1)
data = {}
for row in range(rows):
color = self.index(row, 0).data()
grp = self.index(row, 1).data()
done = self.index(row, 2).data()
vtxs = self.groups[row][3]
#index = self.createIndex(row,0)
data[grp] = [grp, color, done, vtxs]
return data
def queryVtx(self, vtx):
data = self.getData()
for key in data:
vtxs = data[key][3]
if vtx in vtxs:
return data[key][0]
else:
return False
class ColorDelegate(QStyledItemDelegate):
def createEditor(self, parent, option, index):
dialog = QColorDialog(parent)
return dialog
def setEditorData(self, editor, index):
color = index.data(Qt.BackgroundRole)
editor.setCurrentColor(color)
def setModelData(self, editor, model, index):
color = editor.currentColor()
model.setData(index, color, Qt.BackgroundRole)
class Table(QTableView):
def __init__(self, *args, **kwargs):
QTableView.__init__(self, *args, **kwargs)
self.setItemDelegateForColumn(0, ColorDelegate(self))
hHeader = self.horizontalHeader()
#hHeader.setSectionResizeMode(QHeaderView.Fixed);
self.setSelectionBehavior(QAbstractItemView.SelectRows)
self.setSelectionMode(QAbstractItemView.SingleSelection)
vHeader = self.verticalHeader()
vHeader.hide()
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
w = Table()
model = Model()
w.setModel(model)
model.insertRows(["red", "group1", "no"])
model.insertRows(["blue", "group1", "no"], 0)
w.show()
sys.exit(app.exec_())

Unable to select Checkbox inside TreeView

I tried creating a treeview with checkboxes but I'm unable to select the checkboxes.
on the flag method I had mentioned it as ItemisuserCheckable but still could not get it working...
am I missing something here to enable the selection of checkboxes.
A snippet of the code is:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class StbTreeView(QAbstractListModel):
def __init__(self, args, parent=None):
super(StbTreeView, self).__init__(parent)
self.args = args
print self.args
def rowCount(self, parent):
return len(self.args)
def headerData(self, section, orientation, role):
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
return QString("Select STB's")
def flags(self, index):
row = index.row()
if row:
return Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsEditable | Qt.ItemIsSelectable
def data(self, index, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
row = index.row()
return self.args[row]
if role == Qt.CheckStateRole:
row = index.row()
return QVariant(Qt.Unchecked)
def setData(self, index, value, role):
if role == Qt.CheckStateRole:
if value == Qt.Checked:
row = index.row()
selected_stb = self.args[row]
print 'selected_stb is %s' % selected_stb
print 'Value is %s' % value
self.emit(SIGNAL("dataChanged(QModelIndex,QModelIndex)"),index, index)
return True
#return QVariant(Qt.Checked)
def main():
myapp = QApplication(sys.argv)
data = ['STB1', 'STB2', 'STB3', 'STB4', 'STB5', 'STB6', 'STB7', 'STB8']
model = StbTreeView(data)
tree_view = QTreeView()
tree_view.show()
tree_view.setModel(model)
myapp.exec_()
if __name__ == '__main__':
main()
you need to hold somewhere current item state (checked\unchecked) and change it once setdata() method is called. Your items are always unchecked because you're always returning QVariant(Qt.Unchecked) for them in the data() method.
I've changed a bit your code, see it would work for you:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class TestItem():
def __init__(self, name, checked):
self.checked = checked
self.name = name
class StbTreeView(QAbstractListModel):
def __init__(self, args, parent=None):
super(StbTreeView, self).__init__(parent)
self.args = []
for item_name in args:
self.args.append(TestItem(item_name, False))
for item in self.args:
print item.name
def rowCount(self, parent):
return len(self.args)
def headerData(self, section, orientation, role):
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
return QString("Select STB's")
def flags(self, index):
return Qt.ItemIsUserCheckable | Qt.ItemIsEditable | Qt.ItemIsSelectable | Qt.ItemIsEnabled
def data(self, index, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
row = index.row()
print self.args[row].name
return self.args[row].name
if role == Qt.CheckStateRole:
row = index.row()
print self.args[row].checked
if self.args[row].checked == False:
return QVariant(Qt.Unchecked)
else:
return QVariant(Qt.Checked)
def setData(self, index, value, role):
if role == Qt.CheckStateRole:
row = index.row()
self.args[row].checked = not self.args[row].checked
return True
def main():
myapp = QApplication(sys.argv)
data = ['STB1', 'STB2', 'STB3', 'STB4', 'STB5', 'STB6', 'STB7', 'STB8']
model = StbTreeView(data)
tree_view = QTreeView()
tree_view.show()
tree_view.setModel(model)
myapp.exec_()
if __name__ == '__main__':
main()
hope this helps, regards
Thanks it really worked for me. My Original requirement was to call this view/model on a combo box. I tried calling this but it did not work ... I'm able to see the view inside the combo box but unable to select any of the check boxes. I tried quite a few possibility but did not succeed..
Did a slight modification on your code to call from combo box.
the modified code is:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class TestItem():
def __init__(self, name, checked):
self.checked = checked
self.name = name
class StbTreeView(QAbstractListModel):
def __init__(self, args, parent = None):
super(StbTreeView, self).__init__(parent)
self.args = []
for item_name in args:
self.args.append(TestItem(item_name, False))
for item in self.args:
print item.name
#print 'Value of self.args is %s' % self.args
def rowCount(self, parent):
return len(self.args)
def headerData(self, section, orientation, role):
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
return QString("Select STB's")
def flags(self, index):
return Qt.ItemIsUserCheckable | Qt.ItemIsEditable | Qt.ItemIsSelectable | Qt.ItemIsEnabled
def data(self, index, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
row = index.row()
print self.args[row].name
return self.args[row].name
if role == Qt.CheckStateRole:
row = index.row()
print self.args[row].checked
if self.args[row].checked == False:
return QVariant(Qt.Unchecked)
else:
return QVariant(Qt.Checked)
def setData(self, index, value, role):
if role == Qt.CheckStateRole:
row = index.row()
self.args[row].checked = not self.args[row].checked
return True
class Template(QTreeView):
def __init__(self, parent=None):
super(Template, self).__init__(parent)
self.data = ['STB1', 'STB2', 'STB3', 'STB4', 'STB5', 'STB6', 'STB7', 'STB8']
self.MainUI()
def MainUI(self):
self.model = StbTreeView(self.data)
self.setModel(self.model)
def main():
myapp = QApplication(sys.argv)
temp = Template()
temp.show()
myapp.exec_()
if __name__ == '__main__':
main()
The code from combo box:
stb_listview = QComboBox()
view = Template()
stb_listview.setView(view)
stb_listview.setModel(view.model)

Categories

Resources