Related
I wish to add a checkbox to a cell with text in my QTableView:
when a cell is not activated we should see a text and a greyed out checkbox, like this
when we open a delegate editor, we should be able to edit text and to change state of a checkbox
Just for info - further I was planning to do next: when a checkbox is activated - a cell will reject signal for updating text in it, and if checkbox is unchecked - text will be updated when special signal is emitted.
I understand that I should subclass QStyledItemDelegate and re-implement paint method, but as far as I am a beginner I found it difficult to figure out this task.
You can use this example to write and test a code:
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
import pickle
class Mainwindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.table = QtWidgets.QTableView()
self.setCentralWidget(self.table)
self.list = ['item_1', 'item_2','item_3']
self.data = [
[1, 'Blocks γ=500 GOST 31359-2007', self.list[0], 0.18, 0.22],
[2, 'Blocks γ=600 GOST 31359-2008', self.list[0], 0.25, 0.27],
[3, 'Insulation', self.list[0], 0.041, 0.042],
[3, 'Insulation', self.list[0], 0.041, 0.042]
]
self.model = Materials(self.data)
self.table.setModel(self.model)
self.table.setSelectionBehavior(self.table.SelectRows)
self.table.setSelectionMode(self.table.SingleSelection)
for row in range(len(self.model.materials)):
index = self.table.model().index(row,2)
self.table.setIndexWidget(index, self.setting_combobox(index))
def setting_combobox(self, index):
widget = QtWidgets.QComboBox()
list = self.list
widget.addItems(list)
widget.setCurrentIndex(0)
widget.currentTextChanged.connect(lambda value: self.model.setData(index, value))
return widget
class Materials(QtCore.QAbstractTableModel):
def __init__(self, materials = [[]], parent = None):
super(Materials, self).__init__()
self.materials = materials
def rowCount(self, parent):
return len(self.materials)
def columnCount(self, parent):
return len(self.materials[0])
def data(self, index, role):
if role == QtCore.Qt.DisplayRole:
row = index.row()
column = index.column()
value = self.materials[row][column]
return value
if role == QtCore.Qt.EditRole:
row = index.row()
column = index.column()
value = self.materials[row][column]
return value
if role == QtCore.Qt.FontRole:
if index.column() == 0:
boldfont = QtGui.QFont()
boldfont.setBold(True)
return boldfont
def setData(self, index, value, role = QtCore.Qt.EditRole):
if role == QtCore.Qt.EditRole:
row = index.row()
column = index.column()
self.materials[row][column] = value
self.dataChanged.emit(index, index)
return True
return False
def flags(self, index):
return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
if __name__ == '__main__':
app = QtWidgets.QApplication([])
application = Mainwindow()
application.show()
sys.exit(app.exec())
A possible solution is to enable the role Qt.CheckStateRole and modify the position of the checkbox using the delegate. For this, the model must also be modified to store the state of the checkbox.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class CustomDelegate(QtWidgets.QStyledItemDelegate):
def initStyleOption(self, option, index):
value = index.data(QtCore.Qt.CheckStateRole)
if value is None:
model = index.model()
model.setData(index, QtCore.Qt.Unchecked, QtCore.Qt.CheckStateRole)
super().initStyleOption(option, index)
option.direction = QtCore.Qt.RightToLeft
option.displayAlignment = QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter
class Mainwindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.table = QtWidgets.QTableView()
self.setCentralWidget(self.table)
self.list = ["item_1", "item_2", "item_3"]
self.data = [
[1, "Blocks γ=500 GOST 31359-2007", self.list[0], 0.18, 0.22],
[2, "Blocks γ=600 GOST 31359-2008", self.list[0], 0.25, 0.27],
[3, "Insulation", self.list[0], 0.041, 0.042],
[3, "Insulation", self.list[0], 0.041, 0.042],
]
self.model = Materials(self.data)
self.table.setModel(self.model)
self.table.setSelectionBehavior(self.table.SelectRows)
self.table.setSelectionMode(self.table.SingleSelection)
for row in range(len(self.model.materials)):
index = self.table.model().index(row, 2)
self.table.setIndexWidget(index, self.setting_combobox(index))
delegate = CustomDelegate(self.table)
self.table.setItemDelegateForColumn(4, delegate)
self.resize(640, 480)
def setting_combobox(self, index):
widget = QtWidgets.QComboBox()
list = self.list
widget.addItems(list)
widget.setCurrentIndex(0)
widget.currentTextChanged.connect(
lambda value: self.model.setData(index, value)
)
return widget
class Materials(QtCore.QAbstractTableModel):
def __init__(self, materials=[[]], parent=None):
super(Materials, self).__init__()
self.materials = materials
self.check_states = dict()
def rowCount(self, parent):
return len(self.materials)
def columnCount(self, parent):
return len(self.materials[0])
def data(self, index, role):
if role == QtCore.Qt.DisplayRole:
row = index.row()
column = index.column()
value = self.materials[row][column]
return value
if role == QtCore.Qt.EditRole:
row = index.row()
column = index.column()
value = self.materials[row][column]
return value
if role == QtCore.Qt.FontRole:
if index.column() == 0:
boldfont = QtGui.QFont()
boldfont.setBold(True)
return boldfont
if role == QtCore.Qt.CheckStateRole:
value = self.check_states.get(QtCore.QPersistentModelIndex(index))
if value is not None:
return value
def setData(self, index, value, role=QtCore.Qt.EditRole):
if role == QtCore.Qt.EditRole:
row = index.row()
column = index.column()
self.materials[row][column] = value
self.dataChanged.emit(index, index, (role,))
return True
if role == QtCore.Qt.CheckStateRole:
self.check_states[QtCore.QPersistentModelIndex(index)] = value
self.dataChanged.emit(index, index, (role,))
return True
return False
def flags(self, index):
return (
QtCore.Qt.ItemIsEditable
| QtCore.Qt.ItemIsEnabled
| QtCore.Qt.ItemIsSelectable
| QtCore.Qt.ItemIsUserCheckable
)
if __name__ == "__main__":
app = QtWidgets.QApplication([])
application = Mainwindow()
application.show()
sys.exit(app.exec())
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.
How can I make the second column actively in edit mode anytime a row is selected in the tableview as seen in this gif below? I'm trying to recreate this in python/pyside.
Ideally I would like to use some sort of item delegate so i could easily handle the keyPressEvents in the columns cell and add the custom (X) clear button. However I'm not sure how to use delegates like this when using ItemModels. So any help in making this task achievable is appreciated.
class ExampleDelegate(QtGui.QStyledItemDelegate):
def createEditor(self, parent, option, index):
line_edit = QtGui.QLineEdit(parent)
return line_edit
Here is my code and a screenshot:
import os, sys
from PySide import QtGui, QtCore
class HotkeyItem():
def __init__(self, command, shortcut):
self.command = command
self.shortcut = shortcut
class HotkeysModel(QtCore.QAbstractTableModel):
def __init__(self):
super(HotkeysModel, self).__init__()
self.items = []
self.headers = ['Command','Hotkey']
def clear(self):
self.beginResetModel()
self.items = []
self.endResetModel()
def rowCount(self, parent=QtCore.QModelIndex()):
if parent.isValid():
return 0
return len(self.items)
def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
if orientation == QtCore.Qt.Horizontal:
if role == QtCore.Qt.DisplayRole:
cnt = len(self.headers)
if section < cnt:
return self.headers[section]
return None
def columnCount(self, parent=QtCore.QModelIndex()):
if parent.isValid():
return 0
return len(self.headers)
def index(self, row, column, parent=QtCore.QModelIndex()):
return self.createIndex(row, column, parent)
def addItem(self, item):
self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount())
self.items.append(item)
self.endInsertRows()
def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid():
return
row = index.row()
col = index.column()
if 0 <= row < self.rowCount():
item = self.items[row]
if role == QtCore.Qt.DisplayRole:
if col == 0:
return getattr(item, 'command', 'N/A')
elif col == 1:
return getattr(item, 'shortcut', '')
if role == QtCore.Qt.BackgroundRole:
shortcuts = filter(None, [x.shortcut for x in self.items])
dups = shortcuts.count(getattr(item, 'shortcut', ''))
if dups > 1:
return QtGui.QBrush(QtGui.QColor(255, 50, 50, 255))
elif role == QtCore.Qt.FontRole:
shortcuts = filter(None, [x.shortcut for x in self.items])
dups = shortcuts.count(getattr(item, 'shortcut', ''))
if dups > 1:
fnt = QtGui.QFont()
fnt.setBold(True)
fnt.setItalic(True)
return fnt
return None
def flags(self, index):
if not index.isValid():
return 0
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
class Example(QtGui.QWidget):
def __init__(self, parent=None):
super(Example, self).__init__(parent)
self.resize(600, 400)
model = HotkeysModel()
proxyModel = QtGui.QSortFilterProxyModel()
proxyModel.setFilterKeyColumn(0)
proxyModel.setSortCaseSensitivity(QtCore.Qt.CaseInsensitive)
proxyModel.setSourceModel(model)
self.uiView = QtGui.QTableView()
self.uiView.setSortingEnabled(True)
self.uiView.setModel(proxyModel)
self.uiView.setAlternatingRowColors(True)
self.uiView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
self.uiView.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
self.uiView.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
self.uiView.verticalHeader().hide()
self.uiView.horizontalHeader().show()
lay = QtGui.QVBoxLayout()
lay.addWidget(self.uiView)
self.setLayout(lay)
self.populate()
# connections
selection = self.uiView.selectionModel()
selection.currentRowChanged.connect(self.selection_changed)
# ui->tableView->setCurrentIndex(index);
# ui->tableView->edit(index);
def selection_changed(self, index):
if index.isValid():
row = index.row()
self.uiView.setCurrentIndex(index)
self.uiView.edit(index)
def populate(self):
model = self.uiView.model().sourceModel()
model.clear()
items = [
HotkeyItem(command='Save', shortcut='Ctrl+S'),
HotkeyItem(command='Open', shortcut='Ctrl+O'),
HotkeyItem(command='Close', shortcut='Ctrl+Q'),
HotkeyItem(command='Align Top', shortcut=''),
HotkeyItem(command='Align Bottom', shortcut=''),
HotkeyItem(command='Align Left', shortcut=''),
HotkeyItem(command='Align Right', shortcut=''),
HotkeyItem(command='Align Center', shortcut='Ctrl+O')
]
for x in items:
model.addItem(x)
self.uiView.sortByColumn(0, QtCore.Qt.AscendingOrder)
self.uiView.resizeColumnsToContents()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Part of the problem is that for an item to be editable, it must have the flag QtCore.Qt.ItemIsEditable activated. The other part is that the index that passes selection_changed can be from the item in the first column and not from the second, so using that index you should get the index from the second column.
In Qt5 the clear button is already implemented and it is only activated using setClearButtonEnabled(True) and the icon is changed using qss, but in the case of Qt4 it does not exist, so it must be created to use this answer.
Finally you must also implement the setData() method.
import os
import sys
from PySide import QtGui, QtCore
class LineEdit(QtGui.QLineEdit):
def __init__(self, parent=None):
super(LineEdit, self).__init__(parent)
btnSize = self.sizeHint().height() - 5
self.clearButton = QtGui.QToolButton(self)
icon = QtGui.QIcon("clear.png")
self.clearButton.setIcon(icon)
self.clearButton.setCursor(QtCore.Qt.ArrowCursor)
self.clearButton.setStyleSheet("QToolButton { border: none; padding: 2px}")
self.clearButton.setFixedSize(btnSize, btnSize)
self.clearButton.hide()
frameWidth = self.style().pixelMetric(QtGui.QStyle.PM_DefaultFrameWidth)
self.setStyleSheet("QLineEdit{{ padding-right: {}px }}".format(btnSize - frameWidth))
self.setMinimumHeight(self.sizeHint().height())
self.clearButton.clicked.connect(self.clear)
self.textChanged.connect(self.onTextChanged)
def resizeEvent(self, event):
frameWidth = self.style().pixelMetric(QtGui.QStyle.PM_DefaultFrameWidth)
self.clearButton.move(self.width() - self.clearButton.width() - frameWidth, 0)
def onTextChanged(self, text):
self.clearButton.setVisible(text != "")
class Delegate(QtGui.QStyledItemDelegate):
def createEditor(self, parent, option, index):
editor = LineEdit(parent)
font = index.data(QtCore.Qt.FontRole)
editor.setFont(font)
return editor
def setEditorData(self, editor, index):
text = index.data()
editor.setText(text)
def setModelData(self, editor, model, index):
model.setData(index, editor.text())
class HotkeyItem():
def __init__(self, command, shortcut):
self.command = command
self.shortcut = shortcut
class HotkeysModel(QtCore.QAbstractTableModel):
def __init__(self):
super(HotkeysModel, self).__init__()
self.items = []
self.headers = ['Command','Hotkey']
def clear(self):
self.beginResetModel()
self.items = []
self.endResetModel()
def rowCount(self, parent=QtCore.QModelIndex()):
if parent.isValid():
return 0
return len(self.items)
def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
if orientation == QtCore.Qt.Horizontal:
if role == QtCore.Qt.DisplayRole:
cnt = len(self.headers)
if section < cnt:
return self.headers[section]
return None
def columnCount(self, parent=QtCore.QModelIndex()):
if parent.isValid():
return 0
return len(self.headers)
def addItem(self, item):
self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount())
self.items.append(item)
self.endInsertRows()
def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid():
return
row = index.row()
col = index.column()
if 0 <= row < self.rowCount():
item = self.items[row]
if role == QtCore.Qt.DisplayRole:
if col == 0:
return getattr(item, 'command', 'N/A')
elif col == 1:
return getattr(item, 'shortcut', '')
if role == QtCore.Qt.BackgroundRole:
shortcuts = filter(None, [x.shortcut for x in self.items])
dups = shortcuts.count(getattr(item, 'shortcut', ''))
if dups > 1:
return QtGui.QBrush(QtGui.QColor(255, 50, 50, 255))
elif role == QtCore.Qt.FontRole:
shortcuts = filter(None, [x.shortcut for x in self.items])
dups = shortcuts.count(getattr(item, 'shortcut', ''))
if dups > 1:
fnt = QtGui.QFont()
fnt.setBold(True)
fnt.setItalic(True)
return fnt
def setData(self, index, value, role=QtCore.Qt.EditRole):
if index.isValid():
row = index.row()
col = index.column()
if 0 <= row < self.rowCount() and 0 <= col < self.columnCount():
it = self.items[row]
if col == 0:
it.command = value
elif col == 1:
it.shortcut = value
return True
return False
def flags(self, index):
fl = QtCore.Qt.NoItemFlags
if index.isValid():
fl |= QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
if index.column() == 1:
fl |= QtCore.Qt.ItemIsEditable
return fl
class Example(QtGui.QWidget):
def __init__(self, parent=None):
super(Example, self).__init__(parent)
self.resize(600, 400)
model = HotkeysModel()
proxyModel = QtGui.QSortFilterProxyModel()
proxyModel.setFilterKeyColumn(0)
proxyModel.setSortCaseSensitivity(QtCore.Qt.CaseInsensitive)
proxyModel.setSourceModel(model)
self.uiView = QtGui.QTableView()
self.uiView.setSortingEnabled(True)
self.uiView.setModel(proxyModel)
self.uiView.setAlternatingRowColors(True)
delegate = Delegate(self)
self.uiView.setItemDelegateForColumn(1, delegate)
self.uiView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
self.uiView.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
self.uiView.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
self.uiView.verticalHeader().hide()
self.uiView.horizontalHeader().show()
lay = QtGui.QVBoxLayout()
lay.addWidget(self.uiView)
self.setLayout(lay)
self.populate()
# connections
selection = self.uiView.selectionModel()
selection.currentChanged.connect(self.openEditor)
self.uiView.clicked.connect(self.openEditor)
def openEditor(self, index):
if index.isValid():
ix = index.sibling(index.row(), 1)
self.uiView.setCurrentIndex(ix)
self.uiView.edit(ix)
def populate(self):
model = self.uiView.model().sourceModel()
model.clear()
items = [
HotkeyItem(command='Save', shortcut='Ctrl+S'),
HotkeyItem(command='Open', shortcut='Ctrl+O'),
HotkeyItem(command='Close', shortcut='Ctrl+Q'),
HotkeyItem(command='Align Top', shortcut=''),
HotkeyItem(command='Align Bottom', shortcut=''),
HotkeyItem(command='Align Left', shortcut=''),
HotkeyItem(command='Align Right', shortcut=''),
HotkeyItem(command='Align Center', shortcut='Ctrl+O')
]
for x in items:
model.addItem(x)
self.uiView.sortByColumn(0, QtCore.Qt.AscendingOrder)
self.uiView.resizeColumnsToContents()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
In this example below I have a simple QTableView which is populated using an AbstractModel. Each row in the table displays information related to a class object called Asset. It has a property called Items that contains a list of strings. I want to know how can i populate the QTableView with a combobox displaying this list of strings for each row.
Secondly when a user changes the item selected in the dropdown, i would like to trigger an event so i can later use it to properly change the color of the colored dot to green or red depending on the object's property called 'Status'
The status would indicate if the Current Version (meaning the latest item in the dropdown list) is the chosen item. If its the last item in the list, meaning the latest item, it would be green, otherwise it's red.
The property 'Active' indicates which item in the dropdownlist is currently selected.
If the status is 0 then it's out dated and if the status is 1 that means the latest version in the dropdownlist is being used.
import sys
from PySide import QtGui, QtCore
class Asset(object):
def __init__(self, name, items=None, status=0, active=0):
self._status = 0
self._name = ''
self._items = []
self._active = active
self.name = name
self.items = items if items != None else []
self.status = status
class AssetModel(QtCore.QAbstractTableModel):
attr = ["Name", "Options"]
def __init__(self, *args, **kwargs):
QtCore.QAbstractTableModel.__init__(self, *args, **kwargs)
self._items = []
def clear(self):
self._items = []
self.reset()
def rowCount(self, index=QtCore.QModelIndex()):
return len(self._items)
def columnCount(self, index=QtCore.QModelIndex()):
return len(self.attr)
def addItem(self, sbsFileObject):
self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount())
self._items.append(sbsFileObject)
self.endInsertRows()
def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return AssetModel.attr[section]
return QtCore.QAbstractTableModel.headerData(self, section, orientation, role)
def getItem(self, index):
row = index.row()
if index.isValid() and 0 <= row < self.rowCount():
return index.data(role=QtCore.Qt.UserRole)
return None
def getSelectedItems(self, selection):
objs = []
for i, index in enumerate(selection):
item = self.getItem(index)
objs.append(item)
return objs
def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid():
return None
if 0 <= index.row() < self.rowCount():
item = self._items[index.row()]
col = index.column()
if 0 <= col < self.columnCount():
if role == QtCore.Qt.DisplayRole:
if col == 0:
return getattr(item, 'name', '')
if col == 1:
return (getattr(item, 'items', []))
elif role == QtCore.Qt.UserRole:
if col == 0:
return item
elif role == QtCore.Qt.DecorationRole:
if col == 0:
status = getattr(item, 'status', 0)
col = QtGui.QColor(255,0,0,255)
if status == 1:
col = QtGui.QColor(255,128,0,255)
elif status == 2:
col = QtGui.QColor(255,255,0,255)
px = QtGui.QPixmap(120,120)
px.fill(QtCore.Qt.transparent)
painter = QtGui.QPainter(px)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
px_size = px.rect().adjusted(12,12,-12,-12)
painter.setBrush(col)
painter.setPen(QtGui.QPen(QtCore.Qt.black, 4,
QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin))
painter.drawEllipse(px_size)
painter.end()
return QtGui.QIcon(px)
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.resize(400,300)
# controls
asset_model = QtGui.QSortFilterProxyModel()
asset_model.setSortCaseSensitivity(QtCore.Qt.CaseInsensitive)
asset_model.setSourceModel(AssetModel())
self.ui_assets = QtGui.QTableView()
self.ui_assets.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
self.ui_assets.setModel(asset_model)
self.ui_assets.verticalHeader().hide()
main_layout = QtGui.QVBoxLayout()
main_layout.addWidget(self.ui_assets)
self.setLayout(main_layout)
self.unit_test()
def unit_test(self):
assets = [
Asset('Doug', ['v01', 'v02', 'v03'], 0),
Asset('Amy', ['v10', 'v11', 'v13'], 1),
Asset('Kevin', ['v11', 'v22', 'v53'], 2),
Asset('Leslie', ['v13', 'v21', 'v23'], 0)
]
self.ui_assets.model().sourceModel().clear()
for i, obj in enumerate(assets):
self.ui_assets.model().sourceModel().addItem(obj)
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
You have 2 tasks:
Make your model editable because when using the combobox you must edit the values, in addition you must implement new roles to access all the properties of Asset, for it modify the class Asset:
class Asset(object):
def __init__(self, name, items=[], active=0):
self.active = active
self.name = name
self.items = items
#property
def status(self):
return self.active == len(self.items) - 1
To make an editable model, you must implement the setData() method and enable the Qt.ItemIsEditable flag:
class AssetModel(QtCore.QAbstractTableModel):
attr = ["Name", "Options"]
ItemsRole = QtCore.Qt.UserRole + 1
ActiveRole = QtCore.Qt.UserRole + 2
def __init__(self, *args, **kwargs):
QtCore.QAbstractTableModel.__init__(self, *args, **kwargs)
self._items = []
def flags(self, index):
fl = QtCore.QAbstractTableModel.flags(self, index)
if index.column() == 1:
fl |= QtCore.Qt.ItemIsEditable
return fl
def clear(self):
self.beginResetModel()
self._items = []
self.endResetModel()
def rowCount(self, index=QtCore.QModelIndex()):
return len(self._items)
def columnCount(self, index=QtCore.QModelIndex()):
return len(self.attr)
def addItem(self, sbsFileObject):
self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount())
self._items.append(sbsFileObject)
self.endInsertRows()
def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return AssetModel.attr[section]
return QtCore.QAbstractTableModel.headerData(self, section, orientation, role)
def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid():
return None
if 0 <= index.row() < self.rowCount():
item = self._items[index.row()]
col = index.column()
if role == AssetModel.ItemsRole:
return getattr(item, 'items')
if role == AssetModel.ActiveRole:
return getattr(item, 'active')
if 0 <= col < self.columnCount():
if role == QtCore.Qt.DisplayRole:
if col == 0:
return getattr(item, 'name', '')
if col == 1:
return getattr(item, 'items')[getattr(item, 'active')]
elif role == QtCore.Qt.DecorationRole:
if col == 0:
status = getattr(item, 'status')
col = QtGui.QColor(QtCore.Qt.red) if status else QtGui.QColor(QtCore.Qt.green)
px = QtGui.QPixmap(120, 120)
px.fill(QtCore.Qt.transparent)
painter = QtGui.QPainter(px)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
px_size = px.rect().adjusted(12, 12, -12, -12)
painter.setBrush(col)
painter.setPen(QtGui.QPen(QtCore.Qt.black, 4,
QtCore.Qt.SolidLine,
QtCore.Qt.RoundCap,
QtCore.Qt.RoundJoin))
painter.drawEllipse(px_size)
painter.end()
return QtGui.QIcon(px)
def setData(self, index, value, role=QtCore.Qt.EditRole):
if 0 <= index.row() < self.rowCount():
item = self._items[index.row()]
if role == AssetModel.ActiveRole:
setattr(item, 'active', value)
return True
return QtCore.QAbstractTableModel.setData(self, index, value, role)
Use a delegate, for it you must overwrite the methods createEditor(), setEditorData() and setModelData() where we created the QComboBox, updated the selection of the QComboBox with the information of the model, and updated the model with the selection of the QComboBox. We also use paint() to make the QComboBox persistent.
class AssetDelegate(QtGui.QStyledItemDelegate):
def paint(self, painter, option, index):
if isinstance(self.parent(), QtGui.QAbstractItemView):
self.parent().openPersistentEditor(index)
QtGui.QStyledItemDelegate.paint(self, painter, option, index)
def createEditor(self, parent, option, index):
combobox = QtGui.QComboBox(parent)
combobox.addItems(index.data(AssetModel.ItemsRole))
combobox.currentIndexChanged.connect(self.onCurrentIndexChanged)
return combobox
def onCurrentIndexChanged(self, ix):
editor = self.sender()
self.commitData.emit(editor)
self.closeEditor.emit(editor, QtGui.QAbstractItemDelegate.NoHint)
def setEditorData(self, editor, index):
ix = index.data(AssetModel.ActiveRole)
editor.setCurrentIndex(ix)
def setModelData(self, editor, model, index):
ix = editor.currentIndex()
model.setData(index, ix, AssetModel.ActiveRole)
Then we establish the delegate and pass it as a parent to the QTableView so that it can be persisted automatically:
self.ui_assets.setItemDelegateForColumn(1, AssetDelegate(self.ui_assets))
The complete code can be found at the following link.
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)