[PyQt] QItemDelegate + Hover

Mads Ipsen mpi at comxnet.dk
Mon Apr 20 07:31:46 BST 2009


Hi,

I would like the editor of my ItemDelegate to be triggered when the mouse
is hovered over the item. I've modified the 'spinboxdelegate.py' (example
included below):

* Reimplement the paint method of QItemDelegate
* Call setAttribute(QtCore.Qt.WA_Hover) on the TableViews viewport() method

and managed to make the background change whenever a mouse hovers a table
item.

That's part of the way, but still not what I want: The QSpinBox should
appear when the mouse hovers the item. Any clues on how so to solve this
(my guess is that it must be simple).

Best regards,

Mads

import sys
from PyQt4 import QtCore, QtGui

class SpinBoxDelegate(QtGui.QItemDelegate):
    def __init__(self, parent = None):
        QtGui.QItemDelegate.__init__(self, parent)

    def createEditor(self, parent, option, index):
        editor = QtGui.QSpinBox(parent)
        editor.setMinimum(0)
        editor.setMaximum(100)
        editor.installEventFilter(self)

        return editor

    def setEditorData(self, spinBox, index):
        value, ok = index.model().data(index, QtCore.Qt.DisplayRole).toInt()

        spinBox.setValue(value)

    def setModelData(self, spinBox, model, index):
        spinBox.interpretText()
        value = spinBox.value()

        model.setData(index, QtCore.QVariant(value))

    def updateEditorGeometry(self, editor, option, index):
        editor.setGeometry(option.rect)

    # Modified by me
    def paint(self, painter, option, index):
        if (option.state & QtGui.QStyle.State_MouseOver):
            painter.fillRect(option.rect, QtCore.Qt.red);
        QtGui.QItemDelegate.paint(self, painter, option, index)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)

    model = QtGui.QStandardItemModel(4, 2)
    tableView = QtGui.QTableView()
    tableView.setModel(model)
    tableView.setEditTriggers(QtGui.QAbstractItemView.AllEditTriggers)

    # Modified by me
    tableView.viewport().setAttribute(QtCore.Qt.WA_Hover);

    delegate = SpinBoxDelegate()
    tableView.setItemDelegate(delegate)

    for row in range(4):
        for column in range(2):
            index = model.index(row, column, QtCore.QModelIndex())
            model.setData(index, QtCore.QVariant((row+1) * (column+1)))

    tableView.setWindowTitle("Spin Box Delegate")
    tableView.show()
    sys.exit(app.exec_())


More information about the PyQt mailing list