如何在 PyQt4/PySide 中的 eventfilter 中在 QListWidget 上绘制?

How to paint on top of QListWidget in eventfilter in PyQt4/PySide?

我在 QLable 上试过这个并且它有效,我不想子类化小部件,因为它们是在 .ui 文件中定义的,我只需要做简单的修改所以我想避免委托.如果我将我的代码放在 paintEvent 中它可以工作,但为什么我不能将它放在 eventfilter 中?

好像画的是正方形,但是在listWidgetItem区域下面。

# -*- coding: utf-8 -*-
from PySide.QtCore import *
from PySide.QtGui import *

class xxxx(QListWidget):
    def __init__(self, parent=None):
        super(xxxx, self).__init__(parent)
        self.installEventFilter(self)

    # def paintEvent(self, event):
    #     p = QPainter()
    #     p.begin(self.viewport())
    #     p.setPen(QPen(Qt.black))
    #     p.fillRect(QRect(0, 1, 20, 20), Qt.red)
    #     p.end()

    def eventFilter(self, widget, event):
        if event.type() == QEvent.Paint:
            p = QPainter()
            # p.begin(self.viewport())
            p.begin(widget)
            p.setPen(QPen(Qt.red))
            p.fillRect(QRect(0, 1, 20, 20), Qt.red)
            p.end()
            return True
        return QListWidget.eventFilter(self, widget, event)


if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    view = xxxx()
    view.show()
    sys.exit(app.exec_())

您需要在视口上安装事件过滤器:

class xxxx(QListWidget):
    def __init__(self, parent=None):
        super(xxxx, self).__init__(parent)
        self.viewport().installEventFilter(self)

    def eventFilter(self, widget, event):
        if event.type() == QEvent.Paint and widget is self.viewport():
            p = QPainter()
            p.begin(widget)
            p.setPen(QPen(Qt.red))
            p.fillRect(QRect(0, 1, 20, 20), Qt.red)
            p.end()
            return True
        return super(xxxx, self).eventFilter(widget, event)