pyQt v4 rowsMoved Signal - python

Im pretty new to Qt and have been trying to create a UI where the user will have rows of information and each row represents a stage in a pipeline. Iam trying to achieve that a user can drag and drop the different rows and that will change the order in which the steps occur.
I have achieved the drag and drop of the rows using :
self.tableView.verticalHeader().setMovable(True)
Iam now trying to get the Signal"rowsMoved" to work but cant seem to get it to work in my custom model and delegate. If anyone knows of a way to get this working or of a way to not use this Signla and use another signal to track which row has moved and where it is now moved to. It will be a great help! :)
Thanks everyone
CODE BELOW
class pipelineModel( QAbstractTableModel ):
def __init_( self ):
super( pipelineModel, self ).__init__()
self.stages = []
# Sets up the population of information in the Model
def data( self, index, role=Qt.DisplayRole ):
if (not index.isValid() or not (0 <= index.row() < len(self.stages) ) ):
return QVariant()
column = index.column()
stage = self.stages[ index.row() ] # Retrieves the object from the list using the row count.
if role == Qt.DisplayRole: # If the role is a display role, setup the display information in each cell for the stage that has just been retrieved
if column == NAME:
return QVariant(stage.name)
if column == ID:
return QVariant(stage.id)
if column == PREV:
return QVariant(stage.prev)
if column == NEXT:
return QVariant(stage.next)
if column == TYPE:
return QVariant(stage.assetType)
if column == DEPARTMENT:
return QVariant(stage.depID)
if column == EXPORT:
return QVariant(stage.export)
if column == PREFIX:
return QVariant(stage.prefix)
if column == DELETE:
return QVariant(stage.delete)
elif role == Qt.TextAlignmentRole:
pass
elif role == Qt.TextColorRole:
pass
elif role == Qt.BackgroundColorRole:
pass
return QVariant()
# Sets up the header information for the table
def headerData( self, section, orientation, role = Qt.DisplayRole ):
if role == Qt.TextAlignmentRole:
if orientation == Qt.Horizontal:
return QVariant( int(Qt.AlignLeft|Qt.AlignVCenter))
return QVariant( int(Qt.AlignRight|Qt.AlignVCenter))
if role != Qt.DisplayRole:
return QVariant()
if orientation == Qt.Horizontal: # If Orientation is horizontal then we populate the headings
if section == ID:
return QVariant("ID")
elif section == PREV:
return QVariant("Previouse")
elif section == NEXT:
return QVariant("Next")
elif section == NAME:
return QVariant("Name")
elif section == TYPE:
return QVariant("Type")
elif section == DEPARTMENT:
return QVariant("Department")
elif section == EXPORT:
return QVariant("Export Model")
elif section == PREFIX:
return QVariant("Prefix")
elif section == DELETE:
return QVariant("Delete")
return QVariant( int( section + 1 ) ) # Creates the Numbers Down the Vertical Side
# Sets up the amount of Rows they are
def rowCount( self, index = QModelIndex() ):
count = 0
try:
count = len( self.stages )
except:
pass
return count
# Sets up the amount of columns they are
def columnCount( self, index = QModelIndex() ):
return 9
def rowsMoved( self, row, oldIndex, newIndex ):
print 'ASDASDSA'
# ---------MAIN AREA---------
class pipeline( QDialog ):
def __init__(self, parent = None):
super(pipeline, self).__init__(parent)
self.stages = self.getDBinfo() # gets the stages from the DB and return them as a list of objects
tableLabel = QLabel("Testing Table - Custom Model + Custom Delegate")
self.tableView = QTableView() # Creates a Table View (for now we are using the default one and not creating our own)
self.tableDelegate = pipelineDelegate()
self.tableModel = pipelineModel()
tableLabel.setBuddy( self.tableView )
self.tableView.setModel( self.tableModel )
# self.tableView.setItemDelegate( self.tableDelegate )
layout = QVBoxLayout()
layout.addWidget(self.tableView)
self.setLayout(layout)
self.tableView.verticalHeader().setMovable(True)
self.connect(self.tableModel, SIGNAL("rowsMoved( )"), self.MovedRow) # trying to setup an on moved signal, need to check threw the available slots
# self.connect(self.tableModel, SIGNAL(" rowsAboutToBeMoved(QModelIndex,int,int,QModelIndex ,int)"), self.MovedRow) # trying to setup an on moved signal, need to check threw the available slots

Note: Components connected to this signal use it to adapt to changes in the model's dimensions. It can only be emitted by the QAbstractItemModel implementation, and cannot be explicitly emitted in subclass code.

What you want is to subclass the QTableView, and overload the rowMoved() SLOT
class MyTableView(QtGui.QTableView):
def __init__(self, parent=None):
super(MyTableView, self).__init__(parent)
self.rowsMoved.connect(self.movedRowsSlot)
def rowMoved(self, row, oldIndex, newIndex):
# do something with these or
super(MyTableView, self).rowMoved(row, oldIndex, newIndex)
def movedRowsSlot(self, *args):
print "Moved rows!", args
Edited To show both overloading rowMoved slot, and using rowsMoved signal

Related

Update Object when Checkbox clicked in QTableView

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.

How can i align (center) row data in Python PyQt5 QTableView? [duplicate]

This question already has answers here:
How to align the text to center of cells in a QTableWidget
(3 answers)
How to set text alignment on a column of QTableView programmatically?
(3 answers)
Closed 2 years ago.
I want to align my all rows in model. I compile .ui to .py in 'QtDesigner' and creates form.py. Ui_MainWindow comes from form.py . Can you explain the solve with examples?
Re:I want to align my all rows in model. I compile .ui to .py in 'QtDesigner' and creates form.py. Ui_MainWindow comes from form.py . Can you explain the solve with examples?
class App(Ui_MainWindow):
def __init__(self, window):
self.setupUi(window)
# code...
numbers = [["Thomas","17776661122",❌],["Parker","1777666331",❌],["Michael","17775553322",❌]]
CreateTable()
def CreateTable(self,fromlist):
for i in range(0,len(fromlist)):
self.model.addCustomer(Customer(fromlist[i][0],fromlist[i][1],fromlist[i][2]))
### align code
# code...
This is my QtTableView Model.
class Customer(object):
def __init__(self,name,number,status):
self.name = name
self.number = number
self.status = status
class CustomerTableModel(QtCore.QAbstractTableModel):
ROW_BATCH_COUNT = 15
def __init__(self):
super(CustomerTableModel,self).__init__()
self.headers = [' İsim ',' Telefon No (Örn 9053xx..) ',' Mesaj Durumu ']
self.customers = []
self.rowsLoaded = CustomerTableModel.ROW_BATCH_COUNT
def rowCount(self,index=QtCore.QModelIndex()):
if not self.customers:
return 0
if len(self.customers) <= self.rowsLoaded:
return len(self.customers)
else:
return self.rowsLoaded
def canFetchMore(self,index=QtCore.QModelIndex()):
if len(self.customers) > self.rowsLoaded:
return True
else:
return False
def fetchMore(self,index=QtCore.QModelIndex()):
reminder = len(self.customers) - self.rowsLoaded
itemsToFetch = min(reminder,CustomerTableModel.ROW_BATCH_COUNT)
self.beginInsertRows(QtCore.QModelIndex(),self.rowsLoaded,self.rowsLoaded+itemsToFetch-1)
self.rowsLoaded += itemsToFetch
self.endInsertRows()
def addCustomer(self,customer):
self.beginResetModel()
self.customers.append(customer)
self.endResetModel()
def columnCount(self,index=QtCore.QModelIndex()):
return len(self.headers)
def data(self,index,role=QtCore.Qt.DisplayRole):
col = index.column()
customer = self.customers[index.row()]
if role == QtCore.Qt.DisplayRole:
if col == 0:
return QtCore.QVariant(customer.name)
elif col == 1:
return QtCore.QVariant(customer.number)
elif col == 2:
return QtCore.QVariant(customer.status)
return QtCore.QVariant()
def headerData(self,section,orientation,role=QtCore.Qt.DisplayRole):
if role != QtCore.Qt.DisplayRole:
return QtCore.QVariant()
if orientation == QtCore.Qt.Horizontal:
return QtCore.QVariant(self.headers[section])
return QtCore.QVariant(int(section + 1))
P.S. : Sorry for my English :-)
I found the solution. I added the this line to ...
def data(self,index,role=QtCore.Qt.DisplayRole):
col = index.column()
customer = self.customers[index.row()]
if role == QtCore.Qt.DisplayRole:
if col == 0:
return QtCore.QVariant(customer.name)
elif col == 1:
return QtCore.QVariant(customer.number)
elif col == 2:
return QtCore.QVariant(customer.status)
return QtCore.QVariant()
# ADDED LINES
elif role == QtCore.Qt.TextAlignmentRole:
return QtCore.Qt.AlignCenter
###
did not get your way to create a table on QTableView, but for each item setting this code works to align ;
data = QTableWidget(["17776661122"])
table.setItem(x,y,data).setTextAlignment(Qt.AlignHCenter)

PyQt5: phantom columns when using QTableView.setSortingEnabled and QSortFilterProxyModel

I have a custom Qt table model that allows a user to add both columns and rows after it's been created. I'm trying to display this table using a QSortFilterProxyModel / QTableView setup, but I'm getting strange behavior when I try and enable sorting on the table view. My view launches and displays the added data correctly:
However, when I click on one of the column headers (to sort), phantom columns are added to the view.
Has anyone seen this before or know whats going on? I'm admittedly a novice still with Qt, so maybe I'm just approaching this the wrong way. Thanks.
# -*- mode:python; mode:auto-fill; fill-column:79; coding:utf-8 -*-
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
# =====================================================================
# =====================================================================
class SimpleProxyModel(QSortFilterProxyModel):
def filterAcceptsColumn(self, col, index):
return True
# =====================================================================
# =====================================================================
class SimpleModel(QAbstractTableModel):
def __init__(self):
super(SimpleModel, self).__init__()
self._data = {}
def rowCount(self, index=QModelIndex()):
if len(self._data.values()) > 0:
return len(self._data.values()[0])
else:
return 0
def columnCount(self, index=QModelIndex()):
return len(self._data.keys())
def data( self, index, role = Qt.DisplayRole ):
row, col = index.row(), index.column()
if ( not index.isValid() or
not ( 0 <= row < self.rowCount() ) or
not ( 0 <= col < self.columnCount() ) ):
return QVariant()
if role == Qt.DisplayRole:
return QVariant( self._data[col][row] )
return QVariant()
def addData( self, col, val):
new_col = False
# Turn on flag for new column
if col not in self._data.keys():
new_col = True
if new_col:
self.beginInsertColumns(QModelIndex(), self.columnCount(),self.columnCount())
# Catch this column up with the others by adding blank rows
self._data[col] = [""] * self.rowCount()
self.beginInsertRows(QModelIndex(), self.rowCount(), self.rowCount())
# Add data to each column, either the value specified or a blank
for i in range(self.columnCount()):
if i == col:
self._data[i].append(val)
else:
self._data[i].append( "" )
self.endInsertRows()
if new_col:
self.endInsertColumns()
# =====================================================================
# =====================================================================
class SimpleView(QWidget):
def __init__(self, parent=None):
super(SimpleView, self).__init__(parent)
self._mainmodel = None
self._proxymodel = None
self._tableview = QTableView()
self._tableview.setSortingEnabled(True)
layout = QVBoxLayout()
layout.addWidget( self._tableview )
self.setLayout(layout)
def setModel(self, model):
self._mainmodel = model
proxy = SimpleProxyModel()
proxy.setSourceModel(model)
self._tableview.setModel(proxy)
# =====================================================================
# =====================================================================
app = QApplication([])
v = SimpleView()
m = SimpleModel()
v.setModel( m )
m.addData(0,1)
m.addData(0,2)
m.addData(1,3)
v.show()
app.exec_()
The Qt documentation is fairly clear on this. You must call endInsertRows after beginInsertRows, and endInsertColumns after beginInsertColumns.
The most pertinent point from the last link above is this:
Note: This function emits the columnsAboutToBeInserted() signal which
connected views (or proxies) must handle before the data is inserted.
Otherwise, the views may end up in an invalid state.
So you must call endInsertColum() before beginning any other insertions/deletions.
It looks like the problem was in my SimpleModel.addData method, and is related to how I nested the column and row inserts. If you change this method to first insert new columns, and then insert new rows, the phantom columns don't show up.
def addData( self, col, val):
if col not in self._data.keys():
self.beginInsertColumns(QModelIndex(), self.columnCount(),self.columnCount())
# Catch this column up with the others by adding blank rows
self._data[col] = [""] * self.rowCount()
self.endInsertColumns()
self.beginInsertRows(QModelIndex(), self.rowCount(), self.rowCount())
# Add data to each column, either the value specified or a blank
for i in range(self.columnCount()):
if i == col:
self._data[i].append(val)
else:
self._data[i].append( "" )
self.endInsertRows()

Adding checkBox as vertical header in QtableView

I am trying to have a QTableView of checkboxes, so I can use them for row selections... I have managed to do that, now I want the header Itself to be checkbox so I can check/Uncheck All or any row . I have been looking for days, but couldn't get to do it.
I tried to use setHeaderData to the model, but couldn't do it.
Any help would be appreciated.
I wasn't particularly happy with the C++ version that #tmoreau ported to Python as it didn't:
handle more than one column
handle custom header heights (for example multi-line header text)
use a tri-state checkbox
work with sorting
So I fixed all of those issues, and created an example with a QStandardItemModel which I generally would advocate over trying to create your own model based on QAbstractTableModel.
There are probably still some imperfections, so I welcome suggestions for how to improve it!
import sys
from PyQt4 import QtCore, QtGui
# A Header supporting checkboxes to the left of the text of a subset of columns
# The subset of columns is specified by a list of column_indices at
# instantiation time
class CheckBoxHeader(QtGui.QHeaderView):
clicked=QtCore.pyqtSignal(int, bool)
_x_offset = 3
_y_offset = 0 # This value is calculated later, based on the height of the paint rect
_width = 20
_height = 20
def __init__(self, column_indices, orientation = QtCore.Qt.Horizontal, parent = None):
super(CheckBoxHeader, self).__init__(orientation, parent)
self.setResizeMode(QtGui.QHeaderView.Stretch)
self.setClickable(True)
if isinstance(column_indices, list) or isinstance(column_indices, tuple):
self.column_indices = column_indices
elif isinstance(column_indices, (int, long)):
self.column_indices = [column_indices]
else:
raise RuntimeError('column_indices must be a list, tuple or integer')
self.isChecked = {}
for column in self.column_indices:
self.isChecked[column] = 0
def paintSection(self, painter, rect, logicalIndex):
painter.save()
super(CheckBoxHeader, self).paintSection(painter, rect, logicalIndex)
painter.restore()
#
self._y_offset = int((rect.height()-self._width)/2.)
if logicalIndex in self.column_indices:
option = QtGui.QStyleOptionButton()
option.rect = QtCore.QRect(rect.x() + self._x_offset, rect.y() + self._y_offset, self._width, self._height)
option.state = QtGui.QStyle.State_Enabled | QtGui.QStyle.State_Active
if self.isChecked[logicalIndex] == 2:
option.state |= QtGui.QStyle.State_NoChange
elif self.isChecked[logicalIndex]:
option.state |= QtGui.QStyle.State_On
else:
option.state |= QtGui.QStyle.State_Off
self.style().drawControl(QtGui.QStyle.CE_CheckBox,option,painter)
def updateCheckState(self, index, state):
self.isChecked[index] = state
self.viewport().update()
def mousePressEvent(self, event):
index = self.logicalIndexAt(event.pos())
if 0 <= index < self.count():
x = self.sectionPosition(index)
if x + self._x_offset < event.pos().x() < x + self._x_offset + self._width and self._y_offset < event.pos().y() < self._y_offset + self._height:
if self.isChecked[index] == 1:
self.isChecked[index] = 0
else:
self.isChecked[index] = 1
self.clicked.emit(index, self.isChecked[index])
self.viewport().update()
else:
super(CheckBoxHeader, self).mousePressEvent(event)
else:
super(CheckBoxHeader, self).mousePressEvent(event)
if __name__=='__main__':
def updateModel(index, state):
for i in range(model.rowCount()):
item = model.item(i, index)
item.setCheckState(QtCore.Qt.Checked if state else QtCore.Qt.Unchecked)
def modelChanged():
for i in range(model.columnCount()):
checked = 0
unchecked = 0
for j in range(model.rowCount()):
if model.item(j,i).checkState() == QtCore.Qt.Checked:
checked += 1
elif model.item(j,i).checkState() == QtCore.Qt.Unchecked:
unchecked += 1
if checked and unchecked:
header.updateCheckState(i, 2)
elif checked:
header.updateCheckState(i, 1)
else:
header.updateCheckState(i, 0)
app = QtGui.QApplication(sys.argv)
tableView = QtGui.QTableView()
model = QtGui.QStandardItemModel()
model.itemChanged.connect(modelChanged)
model.setHorizontalHeaderLabels(['Title 1\nA Second Line','Title 2'])
header = CheckBoxHeader([0,1], parent = tableView)
header.clicked.connect(updateModel)
# populate the models with some items
for i in range(3):
item1 = QtGui.QStandardItem('Item %d'%i)
item1.setCheckable(True)
item2 = QtGui.QStandardItem('Another Checkbox %d'%i)
item2.setCheckable(True)
model.appendRow([item1, item2])
tableView.setModel(model)
tableView.setHorizontalHeader(header)
tableView.setSortingEnabled(True)
tableView.show()
sys.exit(app.exec_())
I had the same issue, and find a solution here, in C++. There is no easy solution, you have to create your own header.
Here's my full code with PyQt4. It seems to work with Python2 and Python3.
I also implemented the select all / select none functionality.
import sys
import signal
#import QT
from PyQt4 import QtCore,QtGui
#---------------------------------------------------------------------------------------------------------
# Custom checkbox header
#---------------------------------------------------------------------------------------------------------
#Draw a CheckBox to the left of the first column
#Emit clicked when checked/unchecked
class CheckBoxHeader(QtGui.QHeaderView):
clicked=QtCore.pyqtSignal(bool)
def __init__(self,orientation=QtCore.Qt.Horizontal,parent=None):
super(CheckBoxHeader,self).__init__(orientation,parent)
self.setResizeMode(QtGui.QHeaderView.Stretch)
self.isChecked=False
def paintSection(self,painter,rect,logicalIndex):
painter.save()
super(CheckBoxHeader,self).paintSection(painter,rect,logicalIndex)
painter.restore()
if logicalIndex==0:
option=QtGui.QStyleOptionButton()
option.rect= QtCore.QRect(3,1,20,20) #may have to be adapt
option.state=QtGui.QStyle.State_Enabled | QtGui.QStyle.State_Active
if self.isChecked:
option.state|=QtGui.QStyle.State_On
else:
option.state|=QtGui.QStyle.State_Off
self.style().drawControl(QtGui.QStyle.CE_CheckBox,option,painter)
def mousePressEvent(self,event):
if self.isChecked:
self.isChecked=False
else:
self.isChecked=True
self.clicked.emit(self.isChecked)
self.viewport().update()
#---------------------------------------------------------------------------------------------------------
# Table Model, with checkBoxed on the left
#---------------------------------------------------------------------------------------------------------
#On row in the table
class RowObject(object):
def __init__(self):
self.col0="column 0"
self.col1="column 1"
class Model(QtCore.QAbstractTableModel):
def __init__(self,parent=None):
super(Model,self).__init__(parent)
#Model= list of object
self.myList=[RowObject(),RowObject()]
#Keep track of which object are checked
self.checkList=[]
def rowCount(self,QModelIndex):
return len(self.myList)
def columnCount(self,QModelIndex):
return 2
def addOneRow(self,rowObject):
frow=len(self.myList)
self.beginInsertRows(QtCore.QModelIndex(),row,row)
self.myList.append(rowObject)
self.endInsertRows()
def data(self,index,role):
row=index.row()
col=index.column()
if role==QtCore.Qt.DisplayRole:
if col==0:
return self.myList[row].col0
if col==1:
return self.myList[row].col1
elif role==QtCore.Qt.CheckStateRole:
if col==0:
if self.myList[row] in self.checkList:
return QtCore.Qt.Checked
else:
return QtCore.Qt.Unchecked
def setData(self,index,value,role):
row=index.row()
col=index.column()
if role==QtCore.Qt.CheckStateRole and col==0:
rowObject=self.myList[row]
if rowObject in self.checkList:
self.checkList.remove(rowObject)
else:
self.checkList.append(rowObject)
index=self.index(row,col+1)
self.dataChanged.emit(index,index)
return True
def flags(self,index):
if index.column()==0:
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsUserCheckable
return QtCore.Qt.ItemIsEnabled
def headerData(self,section,orientation,role):
if role==QtCore.Qt.DisplayRole:
if orientation==QtCore.Qt.Horizontal:
if section==0:
return "Title 1"
elif section==1:
return "Title 2"
def headerClick(self,isCheck):
self.beginResetModel()
if isCheck:
self.checkList=self.myList[:]
else:
self.checkList=[]
self.endResetModel()
if __name__=='__main__':
app=QtGui.QApplication(sys.argv)
#to be able to close with ctrl+c
signal.signal(signal.SIGINT, signal.SIG_DFL)
tableView=QtGui.QTableView()
model=Model(parent=tableView)
header=CheckBoxHeader(parent=tableView)
header.clicked.connect(model.headerClick)
tableView.setModel(model)
tableView.setHorizontalHeader(header)
tableView.show()
sys.exit(app.exec_())
NB: You could store the rows in self.checkList. In my case, I often have to delete rows in random position so it was not sufficient.

abstractTableModel to display two sets of interdependent data in PySide

I'm building a python/PySide tool for cinematography. I created an object which represents a shot. It has properties for start time, end time, and a list of references to actor objects. The actor object has simple properties (name, build, age, etc) and can be shared between shots.
I want to display this in two table views in PySide. One table view lists the shots (and properties in columns), while the other displays actors referenced in the selected shots. If no shots are selected, the second table view is empty. If multiple shots are selected, all referenced actors are displayed in the actor table view.
I created an abstractTableModel for my shot data and everything is working correctly for the shot data in its corresponding table view. However I'm not sure how to even approach the table view for the actors. Should I use another abstractTableModel for the actors? I can't seem to figure out how to feed/connect the data to the second table view for actors contained in selected shots using a abstractTableModel.
I think part of my issue is that I only want to display the actor information once, regardless of whether multiple selected shots reference the same actor. After multiple failed attempts, I'm thinking that I need to redirect and parse the selected shot information (their actor list property) into a custom property of the main window to contain a list of all referenced actor indices and make an abstractTableModel which uses this to fetch the actual actor properties for display. I'm not fully confident this will work, not to mention my gut tells me this is a messy approach, so I've come here for advice.
Is this the correct approach? If not, what's the 'correct' way of setting this up in PySide/python.
Please keep in mind this is my first foray in data models and PySide.
Here's the shot model.
class ShotTableModel(QtCore.QAbstractTableModel):
def __init__(self, data=[], parent=None, *args):
super(ShotTableModel, self).__init__(parent)
self._data = data
def rowCount(self, parent):
return len(self._data.shots)
def columnCount(self, parent):
return len(self._data._headers_shotList)
def getItemFromIndex(self, index):
if index.isValid():
item = self._data.shots[index.row()]
if item:
return item
return None
def flags(self, index):
if index.isValid():
item = self.getItemFromIndex(index)
return item.qt_flags(index.column())
def data(self, index, role):
if not index.isValid():
return None
item = self.getItemFromIndex(index)
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
return item.qt_data(index.column())
if role == QtCore.Qt.CheckStateRole:
if index.column() is 0:
return item.qt_checked
# if role == QtCore.Qt.BackgroundColorRole:
# return QtGui.QBrush()
# if role == QtCore.Qt.FontRole:
# return QtGui.QFont()
if role == QtCore.Qt.DecorationRole:
if index.column() == 0:
resource = item.qt_resource()
return QtGui.QIcon(QtGui.QPixmap(resource))
if role == QtCore.Qt.ToolTipRole:
return item.qt_toolTip()
return None
def setData(self, index, value, role = QtCore.Qt.EditRole):
if index.isValid():
item = self.getItemFromIndex(index)
if role == QtCore.Qt.EditRole:
item.qt_setData(index.column(), value)
self.dataChanged.emit(index, index)
return value
if role == QtCore.Qt.CheckStateRole:
if index.column() is 0:
item.qt_checked = value
return True
return value
def headerData(self, section, orientation, role):
if role == QtCore.Qt.DisplayRole:
if orientation == QtCore.Qt.Horizontal:
return self._data._headers_shotList[section]
def insertRows(self, position, rows, parent = QtCore.QModelIndex()):
self.beginInsertRows(parent, position, position + rows - 1)
for row in range(rows):
newShotName = self._data.getUniqueName(self._data.shots, 'New_Shot')
newShot = Shot(newShotName)
self._data.shots.insert(position, newShot)
self.endInsertRows()
return True
def removeRows(self, position, rows, parent = QtCore.QModelIndex()):
self.beginRemoveRows(parent, position, position + rows - 1)
for row in range(rows):
self._data.shots.pop(position)
self.endRemoveRows()
return True
Here's the data block containing the shot and actor instances. This is what I pass to the shot model.
class ShotManagerData(BaseObject):
def __init__(self, name='', shots=[], actors=[]):
super(ShotManagerData, self).__init__(name)
self._shots = shots # Shot(name="New_Shot", start=0, end=100, actors=[])
self._actors = actors # Actor(name="New_Actor", size="Average", age=0)
self.selectedShotsActors = [] #decided to move to this data block
self._headers_shotList = ['Name', 'Start Frame', 'End Frame']
self._headers_actorList = ['Name', 'Type', 'RootNode', 'File']
def save(self, file=None):
mEmbed.save('ShotManagerData', self)
#classmethod
def load(cls, file=None):
return(mEmbed.load('ShotManagerData'))
#staticmethod
def getUniqueName(dataList, baseName='New_Item'):
name = baseName
increment = 0
list_of_names = [data.name if issubclass(data.__class__, BaseObject) else str(data) for data in dataList]
while name in list_of_names:
increment += 1
name = baseName + '_{0:02d}'.format(increment)
return name
#property
def actors(self):
return self._actors
#property
def shots(self):
return self._shots
def actorsOfShots(self, shots):
actorsOfShots = []
for shot in shots:
for actor in shot.actors:
if actor not in actorsOfShots:
actorsOfShots.append(actor)
return actorsOfShots
def shotsOfActors(self, actors):
shotsOfActors = []
for actor in actors:
for shot in self.shots:
if actor in shot.actors and actor not in shotsOfActors:
shotsOfActors.append(shot)
return shotsOfActors
Finally the main tool.
class ShotManager(form, base):
def __init__(self, parent=None):
super(ShotManager, self).__init__(parent)
self.setupUi(self)
#=======================================================================
# Properties
#=======================================================================
self.data = ShotManagerData() #do any loading if necessary here
self.actorsInSelectedShots = []
#test data
actor1 = Actor('Actor1')
actor2 = Actor('Actor2')
actor3 = Actor('Actor3')
shot1 = Shot('Shot1', [actor1, actor2])
shot2 = Shot('Shot2', [actor2, actor3])
shot3 = Shot('Shot3', [actor1])
self.data.actors.append(actor1)
self.data.actors.append(actor2)
self.data.actors.append(actor3)
self.data.shots.append(shot1)
self.data.shots.append(shot2)
self.data.shots.append(shot3)
#=======================================================================
# Models
#=======================================================================
self._model_shotList = ShotTableModel(self.data)
self._proxyModel_shotList = QtGui.QSortFilterProxyModel()
self._proxyModel_shotList.setSourceModel(self._model_shotList)
self.shotList.setModel(self._proxyModel_shotList) #this is the QTableView
self._selModel_shotList = self.shotList.selectionModel()
self.shotList.setSortingEnabled(True)
self._proxyModel_shotList.setFilterCaseSensitivity(QtCore.Qt.CaseInsensitive)
self._model_actorList = SelectedShotsActorTableModel(self.data)
self._proxyModel_actorList = QtGui.QSortFilterProxyModel()
self._proxyModel_actorList.setSourceModel(self._model_actorList)
self.actorList.setModel(self._proxyModel_actorList)
self._selModel_actorList = self.actorList.selectionModel()
#=======================================================================
# Events
#=======================================================================
self.addShot.clicked.connect(self.addShot_clicked)
self.delShot.clicked.connect(self.delShot_clicked)
self._selModel_shotList.selectionChanged.connect(self.shotList_selectionChanged)
#===========================================================================
# General Functions
#===========================================================================
def getSelectedRows(self, widget):
selModel = widget.selectionModel()
proxyModel = widget.model()
model = proxyModel.sourceModel()
rows = [proxyModel.mapToSource(index).row() for index in selModel.selectedRows()]
rows.sort()
return rows
def getSelectedItems(self, widget):
selModel = widget.selectionModel()
proxyModel = widget.model()
model = proxyModel.sourceModel()
indices = [proxyModel.mapToSource(index) for index in selModel.selectedRows()]
items = [model.getItemFromIndex(index) for index in indices]
return items
#===========================================================================
# Event Functions
#===========================================================================
def addShot_clicked(self):
position = len(self.data.shots)
self._proxyModel_shotList.insertRows(position,1)
def delShot_clicked(self):
rows = self.getSelectedRows(self.shotList)
for row in reversed(rows):
self._proxyModel_shotList.removeRows(row, 1)
def shotList_selectionChanged(self, selected, deselected):
selectedShots = self.getSelectedItems(self.shotList)
print 'SelectedShots: {}'.format(selectedShots)
self.data.selectedShotsActors = self.data.actorsOfShots(selectedShots)
print 'ActorsOfShots: {}'.format(self.data.selectedShotsActors)
self._proxyModel_actorList.setData() # this line reports missing variables
This is the selectedShotActors model:
class SelectedShotsActorTableModel(QtCore.QAbstractTableModel):
def __init__(self, data=[], headers=[], parent=None, *args):
super(SelectedShotsActorTableModel, self).__init__(parent)
self._data = data
def rowCount(self, parent):
return len(self._data.selectedShotsActors)
def columnCount(self, parent):
return len(self._data._headers_actorList)
def getItemFromIndex(self, index):
if index.isValid():
item = self._data.selectedShotsActors[index.row()]
if item:
return item
return None
def flags(self, index):
if index.isValid():
item = self.getItemFromIndex(index)
return item.qt_flags(index.column())
def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid():
return None
item = self.getItemFromIndex(index)
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
return item.qt_data(index.column())
if role == QtCore.Qt.CheckStateRole:
if index.column() is 0:
return item.qt_checked
#
# if role == QtCore.Qt.BackgroundColorRole:
# return QtGui.QBrush()
#
# if role == QtCore.Qt.FontRole:
# return QtGui.QFont()
if role == QtCore.Qt.DecorationRole:
if index.column() == 0:
resource = item.qt_resource()
return QtGui.QIcon(QtGui.QPixmap(resource))
if role == QtCore.Qt.ToolTipRole:
return item.qt_toolTip()
def setData(self, index, value, role = QtCore.Qt.EditRole):
if index.isValid():
item = self.getItemFromIndex(index)
if role == QtCore.Qt.EditRole:
item.qt_setData(index.column(), value)
self.dataChanged.emit(index, index)
return value
if role == QtCore.Qt.CheckStateRole:
if index.column() is 0:
item.qt_checked = value
return True
return value
def headerData(self, section, orientation, role):
if role == QtCore.Qt.DisplayRole:
if orientation == QtCore.Qt.Horizontal:
return self._data._headers_actorList[section]
I would suggest that you use a proxy model. Proxy models do not hold data, they link to an existing model and provide the opportunity to sort, filter or restructure that data as necessary.
Specifically, you can create a QSortFilterProxyModel object with the QTableView's QItemSelectionModel as the source. You can then create a custom filter that constructs a list of actors based on the selected shots. The advantage of this approach is that the proxy model and the view will automatically update as the selection changes. I think this approach adheres to the intent of MVC better than adding code to MainWindow.
See the Custom Sort/Filter Model example for more information on how to do this.
http://qt-project.org/doc/qt-5/qtwidgets-itemviews-customsortfiltermodel-example.html
If you need some background information (I am new to Qt MVC too; I feel your pain) here are some other useful links:
Model-View Programming: Proxy models
http://qt-project.org/doc/qt-5/model-view-programming.html#proxy-models
QSortFilterProxyModel
http://qt-project.org/doc/qt-5/qsortfilterproxymodel.html
My suggestion would be to update the actor model on a selectionChanged() signal from the selectionModel of your shot QTableView.
Each time the signal is emitted (when the shot selection is changed), you need to reset the actor model and then iterate over the selected model indexes within your selection, and get a reference to the shot object for each selected row of your model. For each shot object you can get a list of actors. Then you need to check if the actor is in the actor model, and if it is not, add it in.
Now this is a little inefficient because you are resetting the actor model each time the selection of the shot model is changed. You do have information from the selectionChanged() signal about which rows were deselected, so you could instead remove entries from your actor model when rows of the shot model re deselected, but only if no other selected shot row contains a given actor from your deselected shot.
There are a few options for where this code could live in your project, but I would probably but it where you already have access to the views and models for both actors and shots. This is probably in your subclass of QMainWindow, but without seeing code it is hard to tell!
Hope that helps :)

Categories