【问题标题】:Is it possible to attach one QGraphicsPixmapItem to another?是否可以将一个 QGraphicsPixmapItem 附加到另一个?
【发布时间】:2020-05-09 05:30:19
【问题描述】:

我目前正在 Python 中使用 PyQt4,但我无法在网上找到任何关于在 PyQt UI 上将 GraphicsView 类中的 2 个不同项目组合在一起的信息。这可能吗?

目标是在 GraphicsView 类中将一个 QGraphicsPixmapItem 锚定到另一个,以便当一个人的位置改变或旋转时,另一个人跟随。更重要的是,一个 QGraphicsPixmapItem 是否可以锚定到另一个 QGraphicsPixmapItem 的特定位置?例如。边缘,这样当其他图形项旋转或移动时,锚定的图形项将保持在相对于移动项的确切位置。

【问题讨论】:

  • 也许你应该使用 PyQT5,因为 PyQT4 已经贬值了。
  • 这是一篇很老的帖子了。

标签: python pyqt pyqt4 qgraphicspixmapitem


【解决方案1】:

如果您希望一个项目在最后一个项目旋转或移动时不改变其相对于另一个项目的位置,那么第一个项目是第二个项目的子项目就足够了:

import random
import sys

from PyQt4 import QtCore, QtGui


def create_pixmap(size):
    pixmap = QtGui.QPixmap(size)
    pixmap.fill(QtGui.QColor(*random.sample(range(255), 3)))
    return pixmap


class VariantAnimation(QtCore.QVariantAnimation):
    def updateCurrentValue(self, value):
        pass


if __name__ == "__main__":

    app = QtGui.QApplication(sys.argv)

    w = QtGui.QMainWindow()

    scene = QtGui.QGraphicsScene(w)
    view = QtGui.QGraphicsView(scene)

    parent_item = scene.addPixmap(create_pixmap(QtCore.QSize(150, 150)))
    parent_item.setTransformOriginPoint(parent_item.boundingRect().center())
    parent_item.setFlag(QtGui.QGraphicsItem.ItemIsMovable, True)

    child_item = QtGui.QGraphicsPixmapItem(
        create_pixmap(QtCore.QSize(70, 70)), parent_item
    )
    # or
    # child_item = QtGui.QGraphicsPixmapItem(create_pixmap(QtCore.QSize(70, 70)))
    # child_item.setParentItem(parent_item)

    animation = VariantAnimation(
        startValue=0, endValue=360, duration=1000, loopCount=-1
    )
    animation.valueChanged.connect(parent_item.setRotation)
    animation.start()

    w.setCentralWidget(view)
    w.resize(640, 480)
    w.show()

    sys.exit(app.exec_())

【讨论】:

    猜你喜欢
    • 2014-03-06
    • 1970-01-01
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 2022-11-22
    • 2015-03-09
    相关资源
    最近更新 更多