-2
I am 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 turns out that giving the following error the setPixmap method in the constructor of the Handlerwindow class:
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:
You have Qpixmap in the Qt class tb. I tried it 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 cursor image when passing it 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_())