I'm trying to create an application that does the following: every time the user clicks on an image that will be inside a QLabel, it will open a dialog for the user to open another image.
It happens that you give the following error the setPixmap method in the HandlerWindow class constructor:
self.label.setPixmap(QPixmap("imagem.jpg").scaled(250,150, Qt.KeepAspectRatio))
NameError: name 'QPixmap' is not defined
Complete code:
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QLineEdit,
QHBoxLayout, QMessageBox, QRadioButton, QGroupBox,
QVBoxLayout,QLabel)
class CustomLabel(QLabel):
def __init__(self, parent=None):
super(CustomLabel, self).__init__(parent)
self.setMouseTracking(True)
def mousePressEvent(self, e):
img, re = QFileDialog.getOpenFileName(self, "Selecionar Arquivo", filter="All(*.png *.jpg)")
if re:
self.setPixmap(QPixmap(img).scaled(250, 150, Qt.KeepAspectRatio))
class HandlerWindow(QWidget):
def __init__(self, parent=None):
super(HandlerWindow, self).__init__()
self.resize(300,350)
self.label = CustomLabel(self)
self.label.setPixmap(QPixmap("imagem.jpg").scaled(250,150, Qt.KeepAspectRatio))
def mouseMoveEvent(self, e):
QApplication.setOverrideCursor(Qt.PointingHandCursor)
def leaveEvent(self, e):
QApplication.setOverrideCursor(Qt.ArrowCursor)
def closeEvent(self, e):
e.ignore()
question_close = QMessageBox.question(self, "Fechamento", "Deseja realmente fechar a aplicação?",
QMessageBox.Yes, QMessageBox.No)
if question_close == QMessageBox.Yes:
exit(0)
root = QApplication([])
app = HandlerWindow()
app.show()
sys.exit(root.exec_())
EDIT:
It has QPixmap in the Qt class tb. I tried here and got the same result as using the QtGui class. He is opening the first image and clicking on the image he opens the explorer so I can get a new image to be viewed, but it is not changing the image of the cursor when passing through the image
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QLineEdit,
QHBoxLayout, QMessageBox, QRadioButton, QGroupBox,
QVBoxLayout,QLabel,QFileDialog)
from PyQt5.Qt import (Qt,QPixmap)
import sys
class CustomLabel(QLabel):
def __init__(self, parent=None):
super(CustomLabel, self).__init__(parent)
self.setMouseTracking(True)
def mousePressEvent(self, e):
img, re = QFileDialog.getOpenFileName(self, "Selecionar Arquivo", filter="All(*.png *.jpg)")
if re:
self.setPixmap(QPixmap(img).scaled(800, 800, Qt.KeepAspectRatio))
class HandlerWindow(QWidget):
def __init__(self, parent=None):
super(HandlerWindow, self).__init__()
self.resize(800,650)
self.label = CustomLabel(self)
self.label.setPixmap(QPixmap("imagem.jpg").scaled(800,800, Qt.KeepAspectRatio))
def mouseMoveEvent(self, e):
QApplication.setOverrideCursor(Qt.PointingHandCursor)
def leaveEvent(self, e):
QApplication.setOverrideCursor(Qt.ArrowCursor)
root = QApplication([])
app = HandlerWindow()
app.show()
sys.exit(root.exec_())