Code is almost complete. Here's the deal:
It is python and PySide. I have a QAbstractTableModel and a QTableView.
I cant get deleting rows correctly. I think the problem is somewhere in the indexes of the rows onde I delete one of them...
here is the button delegate I use:
class ButtonDelegate(QItemDelegate):
def __init__(self, parent):
QItemDelegate.__init__(self, parent)
def paint(self, painter, option, index):
widget = QWidget()
layout = QHBoxLayout()
widget.setLayout(layout)
btn = QPushButton("X")
btn.clicked.connect(partial(self.parent().cellButtonClicked, index))
layout.addWidget(btn)
layout.setContentsMargins(2,2,2,2)
if not self.parent().indexWidget(index):
self.parent().setIndexWidget(index, widget)
here's the cellButtonClicked method, it is under the table view:
class Table(QTableView):
def __init__(self, *args, **kwargs):
QTableView.__init__(self, *args, **kwargs)
self.setItemDelegateForColumn(6, ButtonDelegate(self))
self.setItemDelegateForColumn(0, EmptyDelegate(self))
self.setSortingEnabled(True)
def cellButtonClicked(self, index, *args):
model = self.model()
model.removeRow(index.row())
and here is the model removeRow Method:
def removeRow(self, row, parent = QtCore.QModelIndex()):
self.beginRemoveRows(parent, row, row)
array = []
for i in range(7):
if i == 0:
array.append(self.index(row, i).data())
else:
array.append(str(self.index(row, i).data()))
self.cycles.remove(array)
self.endRemoveRows()
# update custom node in maya.
self.getData()
I think that, mainly, the problem is that when I delete a row it does not update the indexes of the model. So when I click again in any delete button it starts de removeRow() with an index the does no match the rowCount of the model anymore, therefore I can't build the array to be removed from the model data.
Did it make sense? if you need more code, tell me what you need.
The problem is caused because you have set the value of the row when you have created each delegate, so its value is not updated.
A possible solution is to use a lambda function to pass a QPersistenModelIndex associated with the temporary QModelIndex, but I have seen that there is an unexpected behavior that is creating a selection, so I called clearSelection().
It is not necessary to connect to the cellButtonClicked slot since you can directly access the model using QModelIndex or QPersistenModelIndex.
class ButtonDelegate(QItemDelegate):
def __init__(self, parent):
QItemDelegate.__init__(self, parent)
def paint(self, painter, option, index):
widget = QWidget()
layout = QHBoxLayout()
widget.setLayout(layout)
btn = QPushButton("X")
ix = QPersistentModelIndex(index)
btn.clicked.connect(lambda ix = ix : self.onClicked(ix))
layout.addWidget(btn)
layout.setContentsMargins(2,2,2,2)
if not self.parent().indexWidget(index):
self.parent().setIndexWidget(index, widget)
def onClicked(self, ix):
model = ix.model()
model.removeRow(ix.row())
self.parent().clearSelection()
Another option is to handle the clicked events through editorEvent since the provided QModelIndex has updated values as shown below:
class ButtonDelegate(QStyledItemDelegate):
def __init__(self, parent):
QStyledItemDelegate.__init__(self, parent)
self.state = QStyle.State_Enabled
def paint(self, painter, option, index):
button = QStyleOptionButton()
button.rect = self.adjustRect(option.rect)
button.text = "X"
button.state = self.state
QApplication.style().drawControl(QStyle.CE_PushButton, button, painter)
def editorEvent(self, event, model, option, index):
if event.type() == QEvent.Type.MouseButtonPress:
self.state = QStyle.State_On
return True
elif event.type() == QEvent.Type.MouseButtonRelease:
r = self.adjustRect(option.rect)
if r.contains(event.pos()):
model.removeRow(index.row())
self.state = QStyle.State_Enabled
return True
#staticmethod
def adjustRect(rect):
r = QRect(rect)
margin = QPoint(2, 2)
r.translate(margin)
r.setSize(r.size()-2*QSize(margin.x(), margin.y()))
return r
In addition to this it is not necessary to iterate through data(), we can delete the row directly:
def removeRow(self, row, parent=QModelIndex()):
self.beginRemoveRows(parent, row, row)
self.cycles.remove(self.cycles[row])
self.endRemoveRows()
self.getData()
In the following link both options are implemented.
Related
How could I rewrite that code bellow for more then one QTableWidget(not only the self.general_table) ? I don't want to put the same code for every table.
class QTableWidgetEnDisabledItem(QtGui.QItemDelegate):
"""
Create a readOnly/editable QTableWidgetItem
"""
def __init__(self, parent, state):
self.state = state
QtGui.QItemDelegate.__init__(self, parent)
def createEditor(self, parent, option, index):
item = QtGui.QLineEdit(parent)
if self.state == "disabled":
item.setReadOnly(True)
elif self.state == "enabled":
item.setEnabled(True)
return item
Execution of the class QTableWidgetEnDisabledItem
self.Size = QTableWidgetEnDisabledItem(self.general_table, "enabled")
self.general_table.setItemDelegateForRow(index.row(),self.Size)
You could create a list with the tables that you have to use a for to execute the commands that you want.
tables = [self.general_table, self.layers_table]
for table in tables:
itemDelegate = QTableWidgetEnDisabledItem(table, "enabled")
table.setItemDelegateForRow(index.row(), itemDelegate)
I am fairly new to PyQt, I'm working on a project that contains a QTableView, with one of its columns displaying system paths. I would like to add a QTreeView so users can click the + or > buttons to expand what is underneath the paths.
Here is my basic implementation:
from PyQt4 import QtGui
from PyQt4 import QtCore
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.resize(600,400)
self.setWindowTitle("My Basic Treeview")
self.treeview = QtGui.QTreeView(self)
self.treeview.model = QtGui.QFileSystemModel()
self.treeview.model.setRootPath('/opt')
self.treeview.setModel(self.treeview.model)
self.treeview.setColumnWidth(0, 200)
self.setCentralWidget(self.treeview)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
Although, in the above case, I get all folders but I just want the /opt path and its underneath folders.
import operator
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class MyWindow(QWidget):
def __init__(self, data_list, header, *args):
QWidget.__init__(self, *args)
# setGeometry(x_pos, y_pos, width, height)
self.setGeometry(300, 200, 570, 450)
self.setWindowTitle("Click on column title to sort")
table_model = MyTableModel(self, data_list, header)
table_view = QTableView()
table_view.setModel(table_model)
# set font
font = QFont("Courier New", 14)
table_view.setFont(font)
# set column width to fit contents (set font first!)
table_view.resizeColumnsToContents()
# enable sorting
table_view.setSortingEnabled(True)
layout = QVBoxLayout(self)
layout.addWidget(table_view)
self.setLayout(layout)
class MyTableModel(QAbstractTableModel):
def __init__(self, parent, mylist, header, *args):
QAbstractTableModel.__init__(self, parent, *args)
self.mylist = mylist
self.header = header
def rowCount(self, parent):
return len(self.mylist)
def columnCount(self, parent):
return len(self.mylist[0])
def data(self, index, role):
if not index.isValid():
return None
elif role != Qt.DisplayRole:
return None
return self.mylist[index.row()][index.column()]
def headerData(self, col, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self.header[col]
return None
# the solvent data ...
header = ['Name', ' Email', ' Status', ' Path']
# use numbers for numeric data to sort properly
data_list = [
('option_A', 'zyro#email.com', 'Not Copied', '/Opt'),
('option_B', 'zyro#email.com', 'Not Copied', '/Users'),
]
app = QApplication([])
win = MyWindow(data_list, header)
win.show()
app.exec_()
Visual example :
I think your question can be divided in two parts:
how, in a QTreeView, the /opt path and its children can be shown, but without showing its siblings. In other words, how is it possible to show the root directory in a QTreeView ;
how can a QTreeView be added to a QTableView.
1. How to include the root directory in a QTreeView :
The root of a QTreeView is the directory for which the content is shown in the view. It is set when calling the method setRootIndex. According to a post by wysota on Qt Centre:
You can't display the invisibleRootItem because it is a fake item used only to have an equivalent of empty QModelIndex.
A workaround would be to set the root directory to the parent of /opt and filtering out the siblings of /opt with a subclass of a QSortFilterProxyModel. Note that I've also reimplemented the sizeHint method which will be necessary for the resizing of the rows of the QTableView:
from PyQt4 import QtGui, QtCore
import os
class MyQTreeView(QtGui.QTreeView):
def __init__(self, path, parent=None):
super(MyQTreeView, self).__init__(parent)
ppath = os.path.dirname(path) # parent of path
self.setFrameStyle(0)
#---- File System Model ----
sourceModel = QtGui.QFileSystemModel()
sourceModel.setRootPath(ppath)
#---- Filter Proxy Model ----
proxyModel = MyQSortFilterProxyModel(path)
proxyModel.setSourceModel(sourceModel)
#---- Filter Proxy Model ----
self.setModel(proxyModel)
self.setHeaderHidden(True)
self.setRootIndex(proxyModel.mapFromSource(sourceModel.index(ppath)))
#--- Hide All Header Sections Except First ----
header = self.header()
for sec in range(1, header.count()):
header.setSectionHidden(sec, True)
def sizeHint(self):
baseSize = super(MyQTreeView,self).sizeHint()
#---- get model index of "path" ----
qindx = self.rootIndex().child(0, 0)
if self.isExpanded(qindx): # default baseSize height will be used
pass
else: # shrink baseShize height to the height of the row
baseSize.setHeight(self.rowHeight(qindx))
return baseSize
class MyQSortFilterProxyModel(QtGui.QSortFilterProxyModel):
def __init__(self, path, parent=None):
super(MyQSortFilterProxyModel, self).__init__(parent)
self.path = path
def filterAcceptsRow(self, row, parent):
model = self.sourceModel()
path_dta = model.index(self.path).data()
ppath_dta = model.index(os.path.dirname(self.path)).data()
if parent.data() == ppath_dta:
if parent.child(row, 0).data() == path_dta:
return True
else:
return False
else:
return True
2. How to add a *QTreeView* to a *QTableView* :
It is possible to add a QTreeView to a QTableView by using a QItemDelegate. The post by Pavel Strakhov greatly helped me for this, since I had never used QTableView in combination with delegates before answering to this question. I always used QTableWidget instead with the setCellWidget method.
Note that I've setup a signal in the MyDelegate class which call the method resizeRowsToContents in the MyTableView class. This way, the height of the rows resize according the the reimplementation of the sizeHint method of the MyQTreeView class.
class MyTableModel(QtCore.QAbstractTableModel):
def __init__(self, parent, mylist, header, *args):
super(MyTableModel, self).__init__(parent, *args)
self.mylist = mylist
self.header = header
def rowCount(self, parent=QtCore.QModelIndex()):
return len(self.mylist)
def columnCount(self, parent=QtCore.QModelIndex()):
return len(self.mylist[0])
def data(self, index, role):
if not index.isValid():
return None
elif role != QtCore.Qt.DisplayRole:
return None
return self.mylist[index.row()][index.column()]
def headerData(self, col, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self.header[col]
return None
class MyDelegate(QtGui.QItemDelegate):
treeViewHeightChanged = QtCore.pyqtSignal(QtGui.QWidget)
def createEditor(self, parent, option, index):
editor = MyQTreeView(index.data(), parent)
editor.collapsed.connect(self.sizeChanged)
editor.expanded.connect(self.sizeChanged)
return editor
def sizeChanged(self):
self.treeViewHeightChanged.emit(self.sender())
class MyTableView(QtGui.QTableView):
def __init__(self, data_list, header, *args):
super(MyTableView, self).__init__(*args)
#---- set up model ----
model = MyTableModel(self, data_list, header)
self.setModel(model)
#---- set up delegate in last column ----
delegate = MyDelegate()
self.setItemDelegateForColumn(3, delegate)
for row in range(model.rowCount()):
self.openPersistentEditor(model.index(row, 3))
#---- set up font and resize calls ----
self.setFont(QtGui.QFont("Courier New", 14))
self.resizeColumnsToContents()
delegate.treeViewHeightChanged.connect(self.resizeRowsToContents)
3. Basic application :
Here is a basic application based on the code you provided in your OP:
if __name__ == '__main__':
header = ['Name', ' Email', ' Status', ' Path']
data_list = [('option_A', 'zyro#email.com', 'Not Copied', '/opt'),
('option_B', 'zyro#email.com', 'Not Copied', '/usr')]
app = QtGui.QApplication([])
win = MyTableView(data_list, header)
win.setGeometry(300, 200, 570, 450)
win.show()
app.exec_()
Which results in:
I have a GUI that consists of a number of sliders, and instead of updating the sliders manually when the underlying data changes, I'd like to store the data in a subclass of QAbstractListModel and have the slider positions update automatically. My subclass looks like this:
from PyQt4 import QtCore
class myDataModel(QtCore.QAbstractListModel):
def __init__(self, initData, parent=None):
super(myDataModel, self).__init__(parent)
self.__data = initData
def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid():
return None
if index.row() > len(self.__data):
return None
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
return self.__data[index.row()]
return None
def rowCount(self, parent=QtCore.QModelIndex()):
return len(self.__data)
def setData(self, index, value, role=QtCore.Qt.EditRole):
if not index.isValid() or role != QtCore.Qt.EditRole:
return False
self.__data[index.row()] = value
self.dataChanged.emit(index, index)
return True
How can I connect this model to the sliders in my GUI so that when the data in the model is changed, the sliders change, and vice versa?
Edit: Here is a mockup of the basic interface I have been working on:
Edit: I still haven't been able to get this to work. Here is my model class:
class dataModel(QtCore.QAbstractListModel):
def __init__(self, initData, parent=None):
super(dataModel, self).__init__(parent)
self.__data = initData
def data(self, index, role=QtCore.Qt.DisplayRole):
if not index.isValid():
return None
if index.row() > len(self.__data):
return None
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
return self.__data[index.row()]
return None
def rowCount(self, parent=QtCore.QModelIndex()):
return len(self.__data)
def setData(self, index, value, role=QtCore.Qt.EditRole):
if not index.isValid() or role != QtCore.Qt.EditRole:
return False
self.__data[index.row()] = value
self.dataChanged.emit(index, index)
return True
Here is the Delegate class:
class sliderDelegate(QtGui.QItemDelegate):
'''
classdocs
'''
def __init__(self, parent=None):
'''
Constructor
'''
super(sliderDelegate, self).__init__(parent)
def setEditorData(self, editor, index):
editor.setValue(index.model().data(index, QtCore.Qt.EditRole))
def setModelData(self, editor, model, index):
model.setData(index, editor.value(), QtCore.Qt.EditRole)
And here is the setup code:
self._model = dataModel([0 for i in xrange(20)])
self._parameterMapper = QtGui.QDataWidgetMapper(mainWindowInstance)
self._parameterMapper.setModel(self._model)
self._parameterMapper.setItemDelegate(sliderDelegate(mainWindowInstance))
self._parameterMapper.addMapping(self._mainWindowInstance.ui.mySlider, 0)
self._parameterMapper.toFirst()
Unfortunately I get the following error when toFirst() is called:
editor.setValue(index.model().data(index, QtCore.Qt.EditRole))
AttributeError: 'NoneType' object has no attribute 'data'
Any help would be appreciated.
So I haven't used QDataWidgetMapper. It does look interesting, but looks more useful for when you want to have multiple widgets updated to a particular row in a model (and be able to switch between rows easily), rather than each row of a model corresponding to the value of a widget (which I think is what you are after).
So this is my rather rough implementation. Hopefully you'll be able to extend it to your application (might need a bit more error checking added, and maybe the ability to link multiple sliders to a single model row, and possibly then extending to other types of widgets)
When you drag the slider, the model is updated to the sliders new value. I've also added a text box where you can type in a number, and click the button, which will set the model to a specific value. You will notice the slider will update to this value!
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
class MainWindow(QtGui.QWidget):
def __init__(self):
super(MainWindow, self).__init__()
main_layout = QtGui.QVBoxLayout()
# Create the model
self.model = MyModel()
# Create a slider and link it to the model
self.slider1 = QtGui.QSlider()
self.model.add_slider(self.slider1)
main_layout.addWidget(self.slider1)
# Add a lineEdit and button to force update the model
# Note that the LineEdit is not linked to the model, so won't update with the slider
self.edit = QtGui.QLineEdit()
button = QtGui.QPushButton('update model')
button.clicked.connect(self.on_clicked)
main_layout.addWidget(self.edit)
main_layout.addWidget(button)
self.setLayout(main_layout)
def on_clicked(self):
self.model.update_model(int(self.edit.text()),self.slider1)
class MyModel(QtGui.QStandardItemModel):
def __init__(self,*args,**kwargs):
super(MyModel,self).__init__(*args,**kwargs)
self._slider_list = {}
self.itemChanged.connect(self.on_item_changed)
def add_slider(self,slider):
if slider in self._slider_list:
raise Exception('You cannot link a slider to the model twice')
item = QtGui.QStandardItem(str(slider.value()))
self._slider_list[slider] = item
self.appendRow(item)
slider.valueChanged.connect(lambda value: self.update_model(value,slider))
def update_model(self,value,slider):
if str(value) != self._slider_list[slider].text():
self._slider_list[slider].setText(str(value))
print 'update_model: %d'%value
def on_item_changed(self,item):
slider = self._slider_list.keys()[self._slider_list.values().index(item)]
if slider.value() != int(item.text()):
slider.setValue(int(item.text()))
print 'on_item_changed: %s'%item.text()
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
Hope that helps!
I'm having problems adding items in my QComboBox. if possible can anyone tell me how to add items using the code below?
class ComboBoxDelegate(QtGui.QItemDelegate):
def __init__(self, owner, itemslist):
QtGui.QItemDelegate.__init__(self, owner)
self.itemslist = itemslist
def paint(self, painter, option, index):
# Get Item Data
value = index.data(QtCore.Qt.DisplayRole).toInt()[0]
#print value
# fill style options with item data
style = QtGui.QApplication.style()
opt = QtGui.QStyleOptionComboBox()
opt.currentText = str(self.itemslist[value])
opt.rect = option.rect
# draw item data as ComboBox
style.drawComplexControl(QtGui.QStyle.CC_ComboBox, opt, painter)
def createEditor(self, parent, option, index):
##get the "check" value of the row
# for row in range(self.parent.model.rowCount(self.parent)):
# print row
self.editor = QtGui.QComboBox(parent)
self.editor.addItems(self.itemslist)
self.editor.setCurrentIndex(0)
self.editor.installEventFilter(self)
self.connect(self.editor,
QtCore.SIGNAL("currentIndexChanged(int)"), self.editorChanged)
return self.editor
def setEditorData(self, editor, index):
value = index.data(QtCore.Qt.DisplayRole).toInt()[0]
editor.setCurrentIndex(value)
def setModelData(self,editor,model,index):
value = editor.currentIndex()
model.setData(index, QtCore.QVariant(value))
def updateEditorGeometry(self, editor, option, index):
editor.setGeometry(option.rect)
def editorChanged(self, index):
check = self.editor.itemText(index)
id_seq = self.parent.selectedIndexes[0][0]
update.updateCheckSeq(self.parent.db, id_seq, check)
this is my output as of now, but i want to add certain items in my combobox.
I have corrected your code. You must add items in combobox when subclass create editor and not in paint. I post only edited code (other code part it's correct):
class ComboBoxDelegate(QtGui.QItemDelegate):
def __init__(self, owner, itemlist):
QtGui.QItemDelegate.__init__(self, owner)
self.itemslist = itemlist
def createEditor(self, parent, option, index):
self.editor = QtGui.QComboBox(parent)
for i in range(0, len(self.itemslist)):
self.editor.addItem(str(self.itemslist[i]))
self.editor.installEventFilter(self)
self.connect(self.editor, QtCore.SIGNAL("currentIndexChanged(int)"), self.editorChanged)
return self.editor
def paint(self, painter, option, index):
value = index.data(QtCore.Qt.DisplayRole).toInt()[0]
opt = QtGui.QStyleOptionComboBox()
opt.text = str(self.itemslist[value])
opt.rect = option.rect
QtGui.QApplication.style().drawControl(QtGui.QStyle.CE_ItemViewItem, opt, painter)
I've been trying to get a tabeView to display one of its columns as comboBoxes. In order to do this, I've written the code for a custom delegate:
class comboBoxDelegate(QStyledItemDelegate):
def __init__(self, model, parent=None):
super(comboBoxDelegate, self).__init__(parent)
self.parent= parent
self.model= model
def createEditor(self, parent, option, index):
if not index.isValid():
return False
self.currentIndex=index
self.comboBox = QComboBox(parent)
self.comboBox.setModel(self.model)
value = index.data(Qt.DisplayRole)
self.comboBox.setCurrentIndex(value)
return self.comboBox
def setEditorData(self, editor, index):
value = index.data(Qt.DisplayRole)
editor.setCurrentIndex(value)
def setModelData(self, editor, model, index):
if not index.isValid():
return False
index.model().setData(index, editor.currentIndex(), Qt.EditRole)
def paint(self, painter, option, index):
currentIndex= index.data(Qt.DisplayRole)
opt= QStyleOptionComboBox()
opt.rect= option.rect
currentComboIndex= self.model.createIndex(currentIndex,0)
opt.currentText= self.model.data(currentComboIndex, Qt.DisplayRole)
QApplication.style().drawComplexControl(QStyle.CC_ComboBox, opt, painter)
The problem is that when I try it the comboBox doesn't show any text at first (only once you've clicked on it). It seems the currentText property isn't working. Any help will be appreciated.
I know this is old, but you really don't have to deal with the painting at all. The combobox doesn't show a value because the combobox current index was likely set as a string instead of an int.
class ComboBoxDelegate(QtGui.QStyledItemDelegate):
"""ComboBox view inside of a Table. It only shows the ComboBox when it is
being edited.
"""
def __init__(self, model, itemlist=None):
super().__init__(model)
self.model = model
self.itemlist = None
# end Constructor
def createEditor(self, parent, option, index):
"""Create the ComboBox editor view."""
if self.itemlist is None:
self.itemlist = self.model.getItemList(index)
editor = QtGui.QComboBox(parent)
editor.addItems(self.itemlist)
editor.setCurrentIndex(0)
editor.installEventFilter(self)
return editor
# end createEditor
def setEditorData(self, editor, index):
"""Set the ComboBox's current index."""
value = index.data(QtCore.Qt.DisplayRole)
i = editor.findText(value)
if i == -1:
i = 0
editor.setCurrentIndex(i)
# end setEditorData
def setModelData(self, editor, model, index):
"""Set the table's model's data when finished editing."""
value = editor.currentText()
model.setData(index, value)
# end setModelData
# end class ComboBoxDelegate
This delegate will only show the combo box when the item is being edited otherwise it shows a normal text item delegate.
You can override QStyledItemDelegate.displayText() method to make your delegate display text without reimplementing paint(). Something like
class comboBoxDelegate(QStyledItemDelegate):
...
def displayText(self, value, locale=None):
return get_appropriate_text_representation_for_value(value)
I think you should call parent class paint() method. Add:
QStyledItemDelegate.paint(self, painter, option, index)
at the end of the paint method in your class, after the call to drawComplexControl