python - PyQt:覆盖 QGraphicsView.drawItems

标签 python pyqt

我需要自定义 QGraphicsView 的绘制过程,所以我重写了 drawItems 方法,如下所示:

self.graphicsview.drawItems=self.drawer.drawItems

其中 self.graphicsview 是一个 QGraphicsView,而 self.drawer 是一个带有方法 drawItems 的自定义类。
在这个方法中,我检查了几个标志来决定如何绘制每个项目,然后调用 item.paint,如下所示:

def drawItems(self, painter, items, options):
    for item in items:
        print "Processing", item
        # ... Do checking ...
        item.paint(painter, options, self.target)

self.target 是 QGraphicsView 的 QGraphicsScene。
然而,一旦到达 item.paint,它就会跳出循环——没有任何错误。如果我在绘画周围放置条件,并为每种可能类型的 QGraphicsItem 粘贴应该执行的代码(通过查看 Qt git-sources),一切正常。
虽然这不是一个很好的解决方案......而且我不明白它是如何跳出循环的?

最佳答案

元素被绘制时出现异常,但没有立即报告。在我的系统(PyQt 4.5.1,Python 2.6)上,当我猴子修补以下方法时没有报告异常:

def drawItems(painter, items, options):
    print len(items)
    for idx, i in enumerate(items):
        print idx, i
        if idx > 5:
            raise ValueError()

输出:

45
0 <PyQt4.QtGui.QGraphicsPathItem object at 0x3585270>
1 <PyQt4.QtGui.QGraphicsSimpleTextItem object at 0x356ca68>
2 <PyQt4.QtGui.QGraphicsSimpleTextItem object at 0x356ce20>
3 <PyQt4.QtGui.QGraphicsSimpleTextItem object at 0x356cc88>
4 <PyQt4.QtGui.QGraphicsSimpleTextItem object at 0x356cc00>
5 <PyQt4.QtGui.QGraphicsSimpleTextItem object at 0x356caf0>
6 <PyQt4.QtGui.QGraphicsSimpleTextItem object at 0x356cb78>

但是,一旦我关闭应用程序,就会打印以下方法:

Exception ValueError: ValueError() in <module 'threading' from '/usr/lib/python2.6/threading.pyc'> ignored

我尝试打印 threading.currentThread(),但无论它是在 monkey-patched drawItems 方法内部还是外部调用,它都会返回相同的线程。

在您的代码中,这可能是因为您将 options(这是一个样式选项对象列表)传递给各个项目而不是相应的选项对象。使用此代码应该会给您正确的结果:

def drawItems(self, painter, items, options):
    for item, option in zip(items, options):
        print "Processing", item
        # ... Do checking ...
        item.paint(painter, option, self.target)

此外,您说 self.target 是场景对象。 documentation for paint()说:

This function, which is usually called by QGraphicsView, paints the contents of an item in local coordinates. ... The widget argument is optional. If provided, it points to the widget that is being painted on; otherwise, it is 0. For cached painting, widget is always 0.

类型是QWidget*QGraphicsScene 继承自 QObject 并且不是小部件,因此这也可能是错误的。

不过,如果根本没有报告异常,或者没有立即报告异常,则表明存在一些不正当行为,您应该联系维护者。

关于python - PyQt:覆盖 QGraphicsView.drawItems,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1142970/

相关文章:

c# - 选择编程语言的建议

python - 如何在 PyQt 中使用 QThreads 双向设置信号和槽?

python - 与装饰器一起使用时 pyqt 信号的问题

python - PyQt MimeData 文件名

Python在PyQt中一键调用两个函数

python - 如何打印可被 3 和 5 整除的 0 到 100 之间的数字?

python telnet 客户端通过带选项卡完成的套接字

python - 我怎样才能制作一个可以将其行折叠成 Qt 中的类别的表格?

python - Pandas - 删除多列中的重复项

python - 这不是与装饰器的工作方式相反吗?