Как поместить несколько QPixmap в класс, который наследуется от QtWidgets.QGraphicsPixmapItem? - PullRequest
0 голосов
/ 12 апреля 2019

Сегодня я застрял с QPixmap.Мой класс унаследован от QtWidgets.QGraphicsPixmapItem и, как в примере ниже.

class graphicButton(QtWidgets.QGraphicsPixmapItem):
    def __init__(self):
        pixmapA = QtGui.QPixmap(r"img.png")

        QtWidgets.QGraphicsPixmapItem.__init__(self, pixmapA)
        self.setFlags(
            self.flags( )
            | QtWidgets.QGraphicsItem.ItemIsSelectable
            | QtWidgets.QGraphicsItem.ItemIsMovable
        )
    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            print("mouse left press")
            event.accept()
        elif event.button() == QtCore.Qt.RightButton:
            print("mouse right press")
            event.accept()
        elif event.button() == QtCore.Qt.MidButton:
            print("mouse middle press")
            event.accept()

Работает нормально, но что, если я захочу поместить более одной картинки?В большинстве случаев, которые я нашел в Google, вам нужно создать несколько QGraphicsPixmapItems.В этом случае я больше не могу наследовать от QGraphicsPixItem и мне нужно перейти на QGraphicsItem или я что-то упустил?

1 Ответ

2 голосов
/ 12 апреля 2019

Простым решением является загрузка изображения, связанного с его положением, например, в следующем случае я помещаю изображения в вершины пятиугольника:

import random
from PyQt5 import QtCore, QtGui, QtWidgets


class GraphicsButton(QtWidgets.QGraphicsPixmapItem):
    def __init__(self, name, pixmap, parent=None):
        super(GraphicsButton, self).__init__(pixmap, parent)
        self.setFlag(QtWidgets.QGraphicsItem.ItemIsSelectable, True)
        self.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True)
        self._name = name

    @property
    def name(self):
        return self._name

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            print("mouse left press")
        elif event.button() == QtCore.Qt.RightButton:
            print("mouse right press")
        elif event.button() == QtCore.Qt.MidButton:
            print("mouse middle press")
        print(self.name)
        super(GraphicsButton, self).mousePressEvent(event)


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        scene = QtWidgets.QGraphicsScene()
        view = QtWidgets.QGraphicsView(scene)
        self.setCentralWidget(view)
        # coordinates of the pentagon
        datas = [
            ("name1", "img0.png", QtCore.QPointF(0, -200)),
            ("name2", "img1.png", QtCore.QPointF(-190, -62)),
            ("name3", "img2.png", QtCore.QPointF(-118, 162)),
            ("name4", "img3.png", QtCore.QPointF(118, 162)),
            ("name5", "img0.png", QtCore.QPointF(190, -62)),
        ]
        for name, path, position in datas:
            item = GraphicsButton(name, QtGui.QPixmap(path))
            scene.addItem(item)
            item.setPos(position)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...