Is it possible to conditionally change the background color of items in a QTableView, using PySide2?
I've read a lot on the model view framework . I cannot figure out if it is necessary to use a Delegate or not. Recently I was able to get a column of checkboxes without a Delegate. I believe that the virtual methods setItemData(index, roles) and itemData(index) could be what I need. However, there is no QMap in PySide2. My model must need somewhere to store the extra information to be used by QtCore.Qt.BackgroundRole (that enum, btw, says "the background brush used for items rendered with the default delegate") If I don't specify a delegate, is the "default delegate" used?. Should I be using QStandardItemModel instead?
In the example code below, how would I get a particular column's background color to be red based on some thresholds (the min and max column are the thresholds?
from PySide2.QtWidgets import (QWidget, QApplication, QTableView,QVBoxLayout)
import sys
from PandasModel2 import PandasModel2
import numpy as np
import pandas as pd
class Example(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(300, 300, 700, 300)
self.setWindowTitle("QTableView")
self.initData()
self.initUI()
def initData(self):
data = pd.DataFrame(np.random.randint(1,10,size=(6,4)), columns=['Test#','MIN', 'MAX','MEASURED'])
data['Test#'] = [1,2,3,4,5,6]
#add the checkable column to the DataFrame
data['Check'] = True
self.model = PandasModel2(data)
def initUI(self):
self.tv = QTableView(self)
self.tv.setModel(self.model)
vbox = QVBoxLayout()
vbox.addWidget(self.tv)
self.setLayout(vbox)
app = QApplication([])
ex = Example()
ex.show()
sys.exit(app.exec_())
And I have a custom model using a pandas dataFrame:
import PySide2.QtCore as QtCore
class PandasModel2(QtCore.QAbstractTableModel):
"""
Class to populate a table view with a pandas dataframe.
This model is non-hierachical.
"""
def __init__(self, data, parent=None):
QtCore.QAbstractTableModel.__init__(self, parent)
self._data = data
def rowCount(self, parent=None):
return self._data.shape[0]
def columnCount(self, parent=None):
return self._data.shape[1]
def data(self, index, role=QtCore.Qt.DisplayRole):
if role==QtCore.Qt.DisplayRole:
if index.column() != 4:
#don't want what determines check state to be shown as a string
if index.isValid():
if index.column() in [1,2,3]:
return '{:.3f}'.format(self._data.iloc[index.row(), index.column()])
if index.column() == 0:
return '{:.2f}'.format(self._data.iloc[index.row(), index.column()])
return str(self._data.iloc[index.row(), index.column()])
if role==QtCore.Qt.CheckStateRole:
if index.column()==4:#had to add this check to get the check boxes only in column 10
if self._data.iloc[index.row(), index.column()] == True:
return QtCore.Qt.Checked
else:
return QtCore.Qt.Unchecked
def getMinimum(self, row):
return self._data.iloc[row, self.getColumnNumber('MIN')]
def getMaximum(self, row):
return self._data.iloc[row, self.getColumnNumber('MAX')]
def getColumnNumber(self, string):
'''
Given a string that identifies a label/column,
return the location of that label/column.
This enables the config file columns to be moved around.
'''
return self._data.columns.get_loc(string)
def headerData(self, col, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self._data.columns[col]
return None
def flags(self, index):
'''
The returned enums indicate which columns are editable, selectable,
checkable, etc.
The index is a QModelIndex.
'''
if index.column() == self.getColumnNumber('Check'):
#print(index.column())
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsUserCheckable
else:
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable
return QtCore.Qt.ItemIsEnabled
def setData(self, index, value, role=QtCore.Qt.DisplayRole):
"""Set the value to the index position depending on Qt::ItemDataRole and data type of the column
Args:
index (QtCore.QModelIndex): Index to define column and row.
value (object): new value.
role (Qt::ItemDataRole): Use this role to specify what you want to do.
Raises:
TypeError: If the value could not be converted to a known datatype.
Returns:
True if value is changed. Calls layoutChanged after update.
False if value is not different from original value.
"""
if not index.isValid():
return False
if role == QtCore.Qt.DisplayRole: #why not edit role?
self._data.iat[index.row(),index.column()]= value
self.layoutChanged.emit()
return True
elif role == (QtCore.Qt.CheckStateRole | QtCore.Qt.DisplayRole):
#this block does get executed when toggling the check boxes,
#verified with debugger. Although the action is the same
#as the block above!
self._data.iat[index.row(),index.column()]= value
self.layoutChanged.emit()
return True
else:
return False
The delegate by default uses the BackgroundRole information if it is available so the solution is just to return a QColor, QBrush or similar.
from PySide2 import QtCore, QtGui
class PandasModel2(QtCore.QAbstractTableModel):
# ...
def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid():
return
if not (0 <= index.row() < self.rowCount() and 0 <= index.column() <= self.columnCount()):
return
value = self._data.iloc[index.row(), index.column()]
if role == QtCore.Qt.DisplayRole:
if index.column() != 4:
if index.column() in [1,2,3]:
return '{:.3f}'.format(value)
if index.column() == 0:
return '{:.2f}'.format(value)
return str(value)
elif role == QtCore.Qt.CheckStateRole:
if index.column() == 4:
return QtCore.Qt.Checked if value else QtCore.Qt.Unchecked
elif index.column() == self.getColumnNumber('MEASURED'):
if role == QtCore.Qt.BackgroundRole:
if self.getMinimum(index.row()) <= value <= self.getMaximum(index.row()):
return QtGui.QColor("red")
Related
I have a working drag and drop example below for reordering rows of the same column length for a qtableview using PyQt5 (with help from this StackOverflow question here). However I am looking to perform the same operation on a qtableview table where one or two rows have merged cells spanning the total number of columns (like the second row in the picture below).
How would be the best way to go about this? Should I remove the merge (clearSpans) at the point of drag/drop and then do a remerge based on the cell value (though when I tried this it did not work), or is there a way to drag/drop reorder with the cell merging intact?
Here's the code which works for row data of equal columns, but fails when a row is merged
from PyQt5.QtGui import QBrush
from PyQt5.QtWidgets import *
from PyQt5.QtCore import QAbstractTableModel, Qt, QModelIndex
class myModel(QAbstractTableModel):
def __init__(self, data, parent=None, *args):
super().__init__(parent, *args)
self._data = data or []
self._headers = ['Type', 'result', 'count']
def rowCount(self, index=None):
return len(self._data)
def columnCount(self, index=None):
return len(self._headers)
def headerData(self, section, orientation, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
if section < 0 or section >= len(self._headers):
return ""
else:
return self._headers[section]
return None
def data(self, index, role=None):
if role == Qt.TextAlignmentRole:
return Qt.AlignHCenter
if role == Qt.ForegroundRole:
return QBrush(Qt.black)
if role == Qt.BackgroundRole:
if (self.index(index.row(), 0).data().startswith('second')):
return QBrush(Qt.green)
else:
if (self.index(index.row(), 1).data()) == 'abc':
return QBrush(Qt.yellow)
if (self.index(index.row(), 1).data()) == 'def':
return QBrush(Qt.blue)
if (self.index(index.row(), 1).data()) == 'ghi':
return QBrush(Qt.magenta)
if role in (Qt.DisplayRole, Qt.EditRole):
return self._data[index.row()][index.column()]
def flags(self, index: QModelIndex) -> Qt.ItemFlags:
return Qt.ItemIsDropEnabled | Qt.ItemIsEnabled | Qt.ItemIsEditable | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled
def supportedDropActions(self) -> bool:
return Qt.MoveAction | Qt.CopyAction
def relocateRow(self, row_source, row_target) -> None:
row_a, row_b = max(row_source, row_target), min(row_source, row_target)
self.beginMoveRows(QModelIndex(), row_a, row_a, QModelIndex(), row_b)
self._data.insert(row_target, self._data.pop(row_source))
self.endMoveRows()
class myTableView(QTableView):
def __init__(self, parent):
super().__init__(parent)
self.verticalHeader().hide()
self.setSelectionBehavior(self.SelectRows)
self.setSelectionMode(self.SingleSelection)
self.setDragDropMode(self.InternalMove)
self.setDragDropOverwriteMode(False)
def dropEvent(self, event):
if (event.source() is not self or
(event.dropAction() != Qt.MoveAction and
self.dragDropMode() != QAbstractItemView.InternalMove)):
super().dropEvent(event)
selection = self.selectedIndexes()
#self.clearSpans()
from_index = selection[0].row() if selection else -1
to_index = self.indexAt(event.pos()).row()
if (0 <= from_index < self.model().rowCount() and
0 <= to_index < self.model().rowCount() and
from_index != to_index):
self.model().relocateRow(from_index, to_index)
event.accept()
super().dropEvent(event)
class sample_data(QMainWindow):
def __init__(self):
super().__init__()
tv = myTableView(self)
tv.setModel(myModel([
["first", 'abc', 123],
["second"],
["third", 'def', 456],
["fourth", 'ghi', 789],
]))
self.setCentralWidget(tv)
tv.setSpan(1, 0, 1, 3)
self.show()
if __name__ == '__main__':
app = QApplication([])
test = sample_data()
raise SystemExit(app.exec_())
The sections of the vertical header can be made movable, so there's no need to implement this functionality yourself. It obviously means the vertical header will be visible, but that can be mitigated by making the sections blank, which will result in a relatively narrow header:
Note that moving sections around (rather than rows) is purely visual - the underlying model is never modified. That shouldn't really matter in practice, though, since the header provides methods to translate from logical to visual indices. And it does bring some additional benefits - for example, it's very easy to return to a previous state (i.e. by using the header's saveState and restoreState methods).
Below is a working demo based on your example. The rows can be re-ordered by dragging and dropping the section headers, or by pressing Alt+Up / Alt+Down when a row is selected. The vertical header can be toggled by pressing F6. The logical rows can be printed by pressing F7.
UPDATE:
I also added support for moving sections around by dragging and dropping the rows themselves.
from PyQt5.QtGui import QBrush
from PyQt5.QtWidgets import *
from PyQt5.QtCore import QAbstractTableModel, Qt, QModelIndex
class myModel(QAbstractTableModel):
def __init__(self, data, parent=None, *args):
super().__init__(parent, *args)
self._data = data or []
self._headers = ['Type', 'result', 'count']
def rowCount(self, index=None):
return len(self._data)
def columnCount(self, index=None):
return len(self._headers)
def headerData(self, section, orientation, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
if section < 0 or section >= len(self._headers):
return ""
else:
return self._headers[section]
else:
return ''
return None
def data(self, index, role=None):
if role == Qt.TextAlignmentRole:
return Qt.AlignHCenter
if role == Qt.ForegroundRole:
return QBrush(Qt.black)
if role == Qt.BackgroundRole:
if (self.index(index.row(), 0).data().startswith('second')):
return QBrush(Qt.green)
else:
if (self.index(index.row(), 1).data()) == 'abc':
return QBrush(Qt.yellow)
if (self.index(index.row(), 1).data()) == 'def':
return QBrush(Qt.blue)
if (self.index(index.row(), 1).data()) == 'ghi':
return QBrush(Qt.magenta)
if role in (Qt.DisplayRole, Qt.EditRole):
return self._data[index.row()][index.column()]
def flags(self, index: QModelIndex) -> Qt.ItemFlags:
return Qt.ItemIsDropEnabled | Qt.ItemIsEnabled | Qt.ItemIsEditable | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled
def supportedDropActions(self) -> bool:
return Qt.MoveAction | Qt.CopyAction
class myTableView(QTableView):
def __init__(self, parent):
super().__init__(parent)
header = self.verticalHeader()
header.setSectionsMovable(True)
header.setSectionResizeMode(QHeaderView.Fixed)
header.setFixedWidth(10)
QShortcut('F7', self, self.getLogicalRows)
QShortcut('F6', self, self.toggleVerticalHeader)
QShortcut('Alt+Up', self, lambda: self.moveRow(True))
QShortcut('Alt+Down', self, lambda: self.moveRow(False))
self.setSelectionBehavior(self.SelectRows)
self.setSelectionMode(self.SingleSelection)
self.setDragDropMode(self.InternalMove)
self.setDragDropOverwriteMode(False)
def dropEvent(self, event):
if (event.source() is not self or
(event.dropAction() != Qt.MoveAction and
self.dragDropMode() != QAbstractItemView.InternalMove)):
super().dropEvent(event)
selection = self.selectedIndexes()
from_index = selection[0].row() if selection else -1
to_index = self.indexAt(event.pos()).row()
if (0 <= from_index < self.model().rowCount() and
0 <= to_index < self.model().rowCount() and
from_index != to_index):
header = self.verticalHeader()
from_index = header.visualIndex(from_index)
to_index = header.visualIndex(to_index)
header.moveSection(from_index, to_index)
event.accept()
super().dropEvent(event)
def toggleVerticalHeader(self):
self.verticalHeader().setHidden(self.verticalHeader().isVisible())
def moveRow(self, up=True):
selection = self.selectedIndexes()
if selection:
header = self.verticalHeader()
row = header.visualIndex(selection[0].row())
if up and row > 0:
header.moveSection(row, row - 1)
elif not up and row < header.count() - 1:
header.moveSection(row, row + 1)
def getLogicalRows(self):
header = self.verticalHeader()
for vrow in range(header.count()):
lrow = header.logicalIndex(vrow)
index = self.model().index(lrow, 0)
print(index.data())
class sample_data(QMainWindow):
def __init__(self):
super().__init__()
tv = myTableView(self)
tv.setModel(myModel([
["first", 'abc', 123],
["second"],
["third", 'def', 456],
["fourth", 'ghi', 789],
]))
self.setCentralWidget(tv)
tv.setSpan(1, 0, 1, 3)
if __name__ == '__main__':
app = QApplication(['Test'])
test = sample_data()
test.setGeometry(600, 100, 350, 185)
test.show()
app.exec_()
I've been learning python a fair it lately and I've come across a few questions here and I'm not entirely sure how to solve them. Each item in the Table is displaying data from a class object called PlayblastJob. This is being built using Python and PySide.
When a user selects a bunch of rows in the Table and clicks 'Randomize Selected Values', the displayed data does not update until the cursor hovers over the table or i click something in the view. How can i refresh the data in all the columns and rows each time the button is clicked?
When a user clicks the 'Checkbox' how can I have that signal set the property 'active' of that rows particular Job object instance?
Code that creates ui in screenshot above:
import os
import sys
import random
from PySide import QtCore, QtGui
class PlayblastJob(object):
def __init__(self, **kwargs):
super(PlayblastJob, self).__init__()
# instance properties
self.active = True
self.name = ''
self.camera = ''
self.renderWidth = 1920
self.renderHeight = 1080
self.renderScale = 1.0
self.status = ''
# initialize attribute values
for k, v in kwargs.items():
if hasattr(self, k):
setattr(self, k, v)
def getScaledRenderSize(self):
x = int(self.renderWidth * self.renderScale)
y = int(self.renderHeight * self.renderScale)
return (x,y)
class JobModel(QtCore.QAbstractTableModel):
HEADERS = ['Name', 'Camera', 'Resolution', 'Status']
def __init__(self):
super(JobModel, self).__init__()
self.items = []
def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
if orientation == QtCore.Qt.Horizontal:
if role == QtCore.Qt.DisplayRole:
return self.HEADERS[section]
return None
def columnCount(self, parent=QtCore.QModelIndex()):
return len(self.HEADERS)
def rowCount(self, parent=QtCore.QModelIndex()):
return len(self.items)
def appendJob(self, *items):
self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount() + len(items) - 1)
for item in items:
assert isinstance(item, PlayblastJob)
self.items.append(item)
self.endInsertRows()
def removeJobs(self, items):
rowsToRemove = []
for row, item in enumerate(self.items):
if item in items:
rowsToRemove.append(row)
for row in sorted(rowsToRemove, reverse=True):
self.beginRemoveRows(QtCore.QModelIndex(), row, row)
self.items.pop(row)
self.endRemoveRows()
def clear(self):
self.beginRemoveRows(QtCore.QModelIndex(), 0, self.rowCount())
self.items = []
self.endRemoveRows()
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 item.name
elif col == 1:
return item.camera
elif col == 2:
width, height = item.getScaledRenderSize()
return '{} x {}'.format(width, height)
elif col == 3:
return item.status.title()
elif role == QtCore.Qt.ForegroundRole:
if col == 3:
if item.status == 'error':
return QtGui.QColor(255, 82, 82)
elif item.status == 'success':
return QtGui.QColor(76, 175, 80)
elif item.status == 'warning':
return QtGui.QColor(255, 193, 7)
elif role == QtCore.Qt.TextAlignmentRole:
if col == 2:
return QtCore.Qt.AlignCenter
if col == 3:
return QtCore.Qt.AlignCenter
elif role == QtCore.Qt.CheckStateRole:
if col == 0:
if item.active:
return QtCore.Qt.Checked
else:
return QtCore.Qt.Unchecked
elif role == QtCore.Qt.UserRole:
return item
return None
class JobQueue(QtGui.QWidget):
'''
Description:
Widget that manages the Jobs Queue
'''
def __init__(self):
super(JobQueue, self).__init__()
self.resize(400,600)
# controls
self.uiAddNewJob = QtGui.QPushButton('Add New Job')
self.uiAddNewJob.setToolTip('Add new job')
self.uiRemoveSelectedJobs = QtGui.QPushButton('Remove Selected')
self.uiRemoveSelectedJobs.setToolTip('Remove selected jobs')
self.jobModel = JobModel()
self.uiJobTableView = QtGui.QTableView()
self.uiJobTableView.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
self.uiJobTableView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
self.uiJobTableView.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.uiJobTableView.setModel(self.jobModel)
self.jobSelection = self.uiJobTableView.selectionModel()
self.uiRandomize = QtGui.QPushButton('Randomize Selected Values')
self.uiPrintJobs = QtGui.QPushButton('Print Jobs')
# sub layouts
self.jobQueueToolsLayout = QtGui.QHBoxLayout()
self.jobQueueToolsLayout.addWidget(self.uiAddNewJob)
self.jobQueueToolsLayout.addWidget(self.uiRemoveSelectedJobs)
self.jobQueueToolsLayout.addStretch()
self.jobQueueToolsLayout.addWidget(self.uiRandomize)
# layout
self.mainLayout = QtGui.QVBoxLayout()
self.mainLayout.addLayout(self.jobQueueToolsLayout)
self.mainLayout.addWidget(self.uiJobTableView)
self.mainLayout.addWidget(self.uiPrintJobs)
self.setLayout(self.mainLayout)
# connections
self.uiAddNewJob.clicked.connect(self.addNewJob)
self.uiRemoveSelectedJobs.clicked.connect(self.removeSelectedJobs)
self.uiRandomize.clicked.connect(self.randomizeSelected)
self.uiPrintJobs.clicked.connect(self.printJobs)
# methods
def addNewJob(self):
name = random.choice(['Kevin','Melissa','Suzie','Eddie','Doug'])
job = PlayblastJob(name=name, camera='Camera001', startFrame=50)
self.jobModel.appendJob(job)
def removeSelectedJobs(self):
jobs = self.getSelectedJobs()
self.jobModel.removeJobs(jobs)
def getSelectedJobs(self):
jobs = [x.data(QtCore.Qt.UserRole) for x in self.jobSelection.selectedRows()]
return jobs
def randomizeSelected(self):
jobs = self.getSelectedJobs()
for job in jobs:
job.camera = random.choice(['Canon','Nikon','Sony','Red'])
job.status = random.choice(['error','warning','success'])
def printJobs(self):
jobs = self.jobModel.items
for job in jobs:
print vars(job)
def main():
app = QtGui.QApplication(sys.argv)
window = JobQueue()
window.show()
app.exec_()
if __name__ == '__main__':
main()
The data in a Qt item model should always be set using setData().
The obvious reason is that the default implementations of item views always call that method whenever the data is modified by the user (eg. manually editing the field), or more programmatically (checking/unchecking a checkable item, like in your case). The other reason is for more consistency with the whole model structure of Qt framework, which should not be ignored.
In any way, the most important thing is that whenever the data is changed, the dataChanged() signal must be emitted. This ensures that all views using the model are notified about the change and eventually update themselves accordingly.
So, while you could manually emit the dataChanged signal from your randomizeSelected function, I would advise you against so.
The dataChanged should only be emitted for the indexes that have actually changed. While you could theoretically emit a generic signal that has the top-left and bottom-right indexes, it's considered bad practice: the view doesn't know what data (and role) has changed and if it gets a signal saying that the whole model has changed it will have to do lots of computations; even if those computations might seem to happen instantly, if you only change even a single index text they become absolutely unnecessary. I know that yours is a very simple model, but for learning purposes it's important to keep this in mind.
On the other hand, if you want to correctly emit the signal for the changed index alone, this means that you need to manually create the model.index() correctly, making the whole structure unnecessary complex, especially if at some point you need more ways to change the data.
In any case, there's no direct and easy way to do so when dealing with checkable items, since it's up to the view to notify the model about the check state change.
Using setData() allows you to have a centralized way to actually set the data to the model and ensure that everything is correctly updated accordingly. Any other method is not only discouraged, but may lead to unexpected behavior (like yours).
Finally, abstract models only have the ItemIsEnabled and ItemIsSelectable flags, so in order to allow checking and uncheking items, you need to override the flags() method too to add the ItemIsUserCheckable flag, and then implement the relative check in the setData().
class JobModel(QtCore.QAbstractTableModel):
# ...
def setData(self, index, data, role=QtCore.Qt.EditRole):
if role in (QtCore.Qt.EditRole, QtCore.Qt.DisplayRole):
if index.column() == 0:
self.items[index.row()].name = data
elif index.column() == 1:
self.items[index.row()].camera = data
# I'm skipping the third column check, as you will probably need some
# custom function there, assuming it should be editable
elif index.column() == 3:
self.items[index.row()].status = data
else:
return False
self.dataChanged.emit(index, index)
return True
elif role == QtCore.Qt.CheckStateRole and index.column() == 0:
self.items[index.row()].active = bool(data)
self.dataChanged.emit(index, index)
return True
return False
def flags(self, index):
flags = super().flags(index)
if index.column() == 0:
flags |= QtCore.Qt.ItemIsUserCheckable
return flags
class JobQueue(QtGui.QWidget):
# ...
def randomizeSelected(self):
for index in self.jobSelection.selectedRows():
self.jobModel.setData(index.sibling(index.row(), 1),
random.choice(['Canon','Nikon','Sony','Red']))
self.jobModel.setData(index.sibling(index.row(), 3),
random.choice(['error','warning','success']))
Note: selectedRows() defaults to the first column, so I'm using index.sibling() to get the correct index of the second and fourth column at the same row.
Note2: PySide has been considered obsolete from years. You should update to PySide2 at least.
I have trouble with trying create my own sorting function with QAbstractItemModel. It works but not case insensitive. I have tried to use QSortFilterProxyModel, but any success. My sort function:
def sort(self, col, order):
self.emit(SIGNAL("layoutAboutToBeChanged()"))
self.tableData = sorted(self.tableData, key=operator.itemgetter(col))
if order == Qt.AscendingOrder:
self.tableData.reverse()
self.emit(SIGNAL("layoutChanged()"))
I am using QTableView. How I could make it case insensitive?
Full example:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import operator
import sys
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
header = ["one", "two"]
tableDict = [["abcdef", "tuvwx"], ["aBcde", "TUvWx"], ["acdef","tUvWX"], ["Acdef", "TUVwx"], ["ACdef", "TUVwx"]]
self.myTable = newTableModel(header, tableDict)
mainLayout = QHBoxLayout()
mainLayout.addWidget(self.myTable.tableView)
self.setLayout(mainLayout)
self.setWindowTitle("Test table")
class newTableModel(QAbstractTableModel):
def __init__(self, header, data, parent=None, *args):
super(newTableModel, self).__init__(parent)
self.tableView = QTableView()
self.tableData = data
self.header = header
self.tableView.setShowGrid(True)
self.tableView.setFrameStyle( QFrame.NoFrame )
self.tableView.setFocusPolicy( Qt.NoFocus )
self.tableView.setSelectionMode( QAbstractItemView.NoSelection )
vHeader = self.tableView.verticalHeader()
vHeader.setVisible(False)
vHeader.setStretchLastSection(False)
hHeader = self.tableView.horizontalHeader()
hHeader.setVisible(True)
hHeader.setStretchLastSection(False)
self.tableView.setSortingEnabled(True)
self.tableView.setModel(self)
self.tableView.resizeRowsToContents()
self.tableView.resizeColumnsToContents()
vHeader.setResizeMode(QHeaderView.ResizeToContents)
self.tableView.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
self.tableView.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
def rowCount(self, parent):
return len(self.tableData)
def columnCount(self, parent):
return len(self.tableData[0])
def data(self, index, role=Qt.DisplayRole):
row = index.row()
col = index.column()
if role == Qt.DisplayRole:
return "{0}".format(self.tableData[row][col])
return None
def setData(self, index, value, role):
if index.isValid():
return True
return False
def flags(self, index):
fl = QAbstractTableModel.flags(self, index)
if index.column() == 0:
fl |= Qt.ItemIsUserCheckable
return fl
def headerData(self, col, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self.header[col]
def sort(self, col, order):
self.emit(SIGNAL("layoutAboutToBeChanged()"))
self.tableData = sorted(self.tableData, key=operator.itemgetter(col))
if order == Qt.AscendingOrder:
self.tableData.reverse()
self.emit(SIGNAL("layoutChanged()"))
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
This table data in example shows sorting - non case sensitive.
You simply need to convert the values to lower (or upper) case in the sort-key that is passed to the sorted function. For improved efficiency, you can also use the reverse argument to avoid doing that in a separate step:
def sort(self, col, order):
self.layoutAboutToBeChanged.emit()
self.tableData = sorted(
self.tableData,
key=lambda row: row[col].lower(),
reverse=(order != Qt.AscendingOrder),
)
self.layoutChanged.emit()
Note that sorted does a stable sort, so equal values (after the key has been applied), will keep their original places. Thus, the second column in your example won't show any changes when it's sorted, since the values are all the "same" (if you ignore case).
UPDATE:
Here's a solution that will work for strings and numbers. It assumes the columns aren't a mixture of the two types:
def sort(self, col, order):
if self.tableData and self.tableData[0]:
self.layoutAboutToBeChanged.emit()
if isinstance(self.tableData[0][col], str):
sortkey = lambda row: row[col].lower()
else:
sortkey = operator.itemgetter(col)
self.tableData = sorted(
self.tableData, key=sortkey,
reverse=(order != Qt.AscendingOrder))
self.layoutChanged.emit()
I'am using PySide2 and want to search a QListView for a value and have that row selected. Like you can with .findText(string_to_search_for) on a QComboBox.
How can i search for a value in a Qlistview and have the index returned?
some additional info:
The model of my QListView is implementation of QAbstractTableModel i've written.
The model is filled with data from a database, in the first column the id and 2nd column the name of the Database item. The QListView is only showing the 2nd column. This is my code for the QTableModel.
from PySide2 import QtGui,QtCore
class TwoColumnTableModel(QtCore.QAbstractTableModel):
def __init__(self, row_data=[], column_data=[], parent=None):
QtCore.QAbstractTableModel.__init__(self, parent)
self.row_data = row_data
self.column_data = column_data
def rowCount(self, parent):
return len(self.row_data)
def columnCount(self, parent):
return len(self.column_data)
def flags(self, index):
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
def data(self, index, role):
if role == QtCore.Qt.DisplayRole:
row = index.row()
column = index.column()
value = self.row_data[row][column]
self.dataChanged.emit(row, column, [])
return value
def headerData(self, section, orientation, role):
if role == QtCore.Qt.DisplayRole:
if orientation == QtCore.Qt.Horizontal:
if section < len(self.column_data):
return self.column_data[section]
else:
return "TEMP COL"
def insertRows(self, position, rows, data=[], parent=QtCore.QModelIndex()):
self.beginInsertRows(parent, position, position + rows - 1)
for i in range(len(data)):
columns = []
row_column1 = data[i][0]
row_column2 = data[i][1]
columns.insert(0, row_column1)
columns.insert(1, row_column2)
self.row_data.insert(position, columns)
self.endInsertRows()
return True
def removeRows(self, position, rows, parent=QtCore.QModelIndex()):
self.beginRemoveRows()
for i in range(rows):
value = self.row_data[position]
self.row_data.remove(value)
self.endRemoveRows()
return True
I ended up creating the following function in QTableModel class:
def find_index_of_value(self, search_string, search_column):
for index in range(self.rowCount(None)):
model_index = self.index(index, 1)
index_value = self.data(model_index, search_column)
if index_value == search_string:
return model_index
The "search_string" being the string i'm looking for and the "search_column" being the column of the model where i want to search for that string. With the return index i can use the setCurrentIndex(index) on my QListView and that's it.
I'm using PYQT for developing an application. my requirement is to insert a tree view with checkbox inside a combobox items. I would like to know how to achieve this?
I have the following code but this does not work.
class CheckboxInsideListbox(QWidget):
def __init__(self, parent = None):
super(CheckboxInsideListbox, self).__init__(parent)
self.setGeometry(250,250,300,300)
self.MainUI()
def MainUI(self):
#stb_label = QLabel("Select STB\'s")
stb_combobox = QComboBox()
length = 10
cb_layout = QVBoxLayout(stb_combobox)
for i in range(length):
c = QCheckBox("STB %i" % i)
cb_layout.addWidget(c)
main_layout = QVBoxLayout()
main_layout.addWidget(stb_combobox)
main_layout.addLayout(cb_layout)
self.setLayout(main_layout)
Please let me know if I'm missing anything here.
You should create a model that support Qt.CheckStateRole in data and SetData methods and the flag Qt.ItemIsUserCheckable in the flags method.
I Paste you here an example i am using in a project, this is a QSortFilterProxyModel generic implementation to use in any model but you can use the same ideas in your model implementation, obviously i am using internal structures in this subclass you have not directly in PyQt and are attached to my internal implementation (self.booleanSet and self.readOnlySet).
def flags(self, index):
if not index.isValid():
return Qt.ItemIsEnabled
if index.column() in self.booleanSet:
return Qt.ItemIsUserCheckable | Qt.ItemIsSelectable | Qt.ItemIsEnabled
elif index.column() in self.readOnlySet:
return Qt.ItemIsSelectable | Qt.ItemIsEnabled
else:
return QSortFilterProxyModel.flags(self, index)
def data(self, index, role):
if not index.isValid():
return QVariant()
if index.column() in self.booleanSet and role in (Qt.CheckStateRole, Qt.DisplayRole):
if role == Qt.CheckStateRole:
value = QVariant(Qt.Checked) if index.data(Qt.EditRole).toBool() else QVariant(Qt.Unchecked)
return value
else: #if role == Qt.DisplayRole:
return QVariant()
else:
return QSortFilterProxyModel.data(self, index, role)
def setData(self, index, data, role):
if not index.isValid():
return False
if index.column() in self.booleanSet and role == Qt.CheckStateRole:
value = QVariant(True) if data.toInt()[0] == Qt.Checked else QVariant(False)
return QSortFilterProxyModel.setData(self, index, value, Qt.EditRole)
else:
return QSortFilterProxyModel.setData(self, index, data, role)
If you really mean to apply a layout to a layout, try adding your widget to your cb_layout. Otherwise get rid of your sublayout.