今天,我陷入了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()
它工作正常,但如果我想放一张照片呢?在我在谷歌中发现的大多数情况下,你需要制作多个QGraphicsPixmapItems。在那种情况下,我不能继承QGraphicsPixItem并且我必须去QGraphicsItem或者我错过了什么?
简单的解决方案是加载与其位置相关联的图像,例如在下面的情况下,我将图像放在五边形的顶点中:
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_())