我正在构建一个 GUI,用于使用QGraphicsScene
和QGraphicsPixmapItem
(下面的代码)在网格中显示照片(来自文件夹)。现在我想在单击其中一个时打开相应的原始图像QGraphicsPixmapItems
。如果我在内部单击,我会覆盖 MousePressEvent 并使程序执行“某些操作” QGraphicsScene
,但是现在我想知道如何检索单击了哪个项目的信息以打开相应的图像。
import sys
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QGraphicsPixmapItem
from PyQt5.QtCore import Qt, QRect
from PyQt5.QtGui import QPixmap
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.showMaximized()
self.central()
def central(self):
self.scene = QtWidgets.QGraphicsScene(QtCore.QRectF(0, 0, 1080, 1000), self)
self.graphicsview = QtWidgets.QGraphicsView(self.scene)
self.setCentralWidget(self.graphicsview)
self.resize(1000, 1000)
list = ['./images/1.JPG', './images/2.JPG', './images/3.JPG', './images/4.JPG',
'./images/5.JPG', './images/6.JPG', './images/7.JPG', './images/8.JPG']
self.t_list = []
for n in range(len(list)):
self.label = QLabel()
self.u_pixmap = QPixmap(list[n])
imgsize = min(self.u_pixmap.width(), self.u_pixmap.height())
rect = QRect(
int((self.u_pixmap.width() - imgsize) / 2),
int((self.u_pixmap.height() - imgsize) / 2), imgsize, imgsize)
self.v_pixmap = self.u_pixmap.copy(rect)
self.pixmap = self.v_pixmap.scaled(200, 200, Qt.KeepAspectRatio, Qt.SmoothTransformation)
self.item = QGraphicsPixmapItem()
self.item.setPixmap(self.pixmap)
self.scene.addItem(self.item)
g = 210
a = 5
y = int(n/a)
x = n - (y * a)
self.item.setOffset(x * g, y * g)
def mousePressEvent(self, event):
if event.button() == Qt.RightButton:
print("item clicked")
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow()
sys.exit(app.exec_())