QPainter not drawing with mouse events - python

I have created a static GUI with a side panel and a custom widget handling the paintEvent.Both of which inherit the QFrame Object.
I begin with loading the image to the PainterFrame which works and then when I try to draw on top of this image it doesn't work despite the mousePressEvent getting triggered.
This is how it looks.
When I hit the choose File button and choose an image it successfully draws the Pixmap on the screen but when I try to draw nothing happens
This is the code for the custom widget PainterFrame and the RegisterFrame which handles the whole GUI.
from PyQt5 import QtWidgets as qtw
from PyQt5 import QtGui as qtg
from PyQt5 import QtCore as qtc
from PyQt5.QtCore import Qt
from PIL import Image
from PIL.ImageQt import ImageQt
import io,sys
class PainterFrame(qtw.QFrame):
def __init__(self, parent=None):
super().__init__(parent)
self.image = None
# Create the properties for the custom object to fit to the parent widget
sizePolicy = qtw.QSizePolicy(qtw.QSizePolicy.Expanding, qtw.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
self.lastPoint = qtc.QPoint()
self.setSizePolicy(sizePolicy)
self.setFrameShape(qtw.QFrame.StyledPanel)
self.setFrameShadow(qtw.QFrame.Plain)
self.show()
def paintEvent(self,event):
if self.image:
painter = qtg.QPainter(self)
self.pixmap = self.imageCovnerter(self.image).scaled(self.size(),qtc.Qt.IgnoreAspectRatio,qtc.Qt.SmoothTransformation)
painter.drawPixmap(self.rect(),self.pixmap)
self.update()
def mousePressEvent(self, event):
painter = qtg.QPainter(self.pixmap)
painter.setPen(qtg.QPen(Qt.red, 5, Qt.SolidLine))
painter.drawPoint(event.x(), event.y())
self.update()
def imageCovnerter(self,imageString):
image = Image.open(io.BytesIO(imageString)).convert("RGBA")
pix = qtg.QPixmap.fromImage(ImageQt(image))
return pix
def setUserImage(self, image):
self.image = image
And the code for the RegisterFrame
from StackedWidgetGUIS.RegisterGUI import Ui_Frame
from Frames.PainterFrame import PainterFrame
from PyQt5 import QtWidgets as qtw
from PyQt5 import QtGui as qtg
from PyQt5 import QtCore as qtc
from PyQt5.QtCore import Qt
import re,os
class RegisterFrame(qtw.QFrame, Ui_Frame):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.painter_frame = PainterFrame()
self.horizontalLayout.addWidget(self.painter_frame)
self.horizontalLayout.setStretch(0, 1)
self.horizontalLayout.setStretch(1, 3)
self.back_button.clicked.connect(self.clearFields)
self.invalid_mail_label = qtw.QLabel("Invalid mail")
self.invalid_mail_label.setStyleSheet("font-family: \'Roboto\';\n"
"font-style: normal;\n"
"font-weight: 200;\n"
"font-size: 14px;\n"
"color: #E61518;")
self.entries_layout.addWidget(self.invalid_mail_label)
self.invalid_mail_label.setVisible(False)
self.email_edit.textChanged.connect(self.checkEmail)
self.choose_file_button.clicked.connect(self.launchDialog)
def clearFields(self):
self.first_name_edit.clear()
self.last_name_edit.clear()
self.email_edit.clear()
self.painter_frame.image = None
def checkEmail(self):
mail_regex = r'\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
if (re.fullmatch(mail_regex, self.email_edit.text())):
self.invalid_mail_label.setVisible(False)
else:
self.invalid_mail_label.setVisible(True)
def launchDialog(self):
file_filter = "Image File (*.png *.jpg)"
self.fileDialog = qtw.QFileDialog.getOpenFileName(parent =self,
caption="Select an image file",
directory= os.getcwd(),
filter=file_filter)
self.painter_frame.setUserImage(self.imageOpener(self.fileDialog[0]))
self.painter_frame.update()
def imageOpener(self, filePath):
with open(filePath, "rb") as f:
img = f.read()
return img

Related

PySide, Pyqt - Is there a way to crop image while saving? [duplicate]

I have opened a image in a QHBoxLayout. I need to crop the opened image and save the cropped image. How I can do this in PySide?
import sys
from PySide import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
hbox = QtGui.QHBoxLayout(self)
pixmap = QtGui.QPixmap("re.png")
lbl = QtGui.QLabel(self)
lbl.setPixmap(pixmap)
self.rect = QtCore.QRect()
hbox.addWidget(lbl)
self.setLayout(hbox)
self.setGeometry(300, 300, 280, 170)
self.setWindowTitle('Open Image')
self.show()
# Tried here to implement Qpen
#self.painter = QtGui.QPainter(self)
#self.painter.setPen(QtGui.QPen(QtCore.Qt.black, 1, QtCore.Qt.SolidLine));
#self.painter.drawRect(self.rect);
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I suggest use class QtGui.QRubberBand to select area of image to crop. (PySide also implements the same functionality as PyQt)
First, implement method mouseMoveEvent (self, QMouseEvent), mouseReleaseEvent (self, QMouseEvent) and mousePressEvent (self, QMouseEvent) (More infomation read in QtGui.QRubberBand class reference).
Next, get last geometry of QtGui.QRubberBand to crop image by use QRect QWidget.geometry (self).
Last, Use QPixmap QPixmap.copy (self, QRect rect = QRect()) to crop image by put geometry from crop area. And save image it by use bool QPixmap.save (self, QString fileName, str format = None, int quality = -1).
Example;
import sys
from PyQt4 import QtGui, QtCore
class QExampleLabel (QtGui.QLabel):
def __init__(self, parentQWidget = None):
super(QExampleLabel, self).__init__(parentQWidget)
self.initUI()
def initUI (self):
self.setPixmap(QtGui.QPixmap('input.png'))
def mousePressEvent (self, eventQMouseEvent):
self.originQPoint = eventQMouseEvent.pos()
self.currentQRubberBand = QtGui.QRubberBand(QtGui.QRubberBand.Rectangle, self)
self.currentQRubberBand.setGeometry(QtCore.QRect(self.originQPoint, QtCore.QSize()))
self.currentQRubberBand.show()
def mouseMoveEvent (self, eventQMouseEvent):
self.currentQRubberBand.setGeometry(QtCore.QRect(self.originQPoint, eventQMouseEvent.pos()).normalized())
def mouseReleaseEvent (self, eventQMouseEvent):
self.currentQRubberBand.hide()
currentQRect = self.currentQRubberBand.geometry()
self.currentQRubberBand.deleteLater()
cropQPixmap = self.pixmap().copy(currentQRect)
cropQPixmap.save('output.png')
if __name__ == '__main__':
myQApplication = QtGui.QApplication(sys.argv)
myQExampleLabel = QExampleLabel()
myQExampleLabel.show()
sys.exit(myQApplication.exec_())
I would use QImage's copy method:
im2 = im.copy(self.rect)
im2.save(...)
import sys
from PyQt5 import QtGui, QtCore,QtWidgets
from PyQt5.QtWidgets import QRubberBand, QLabel, QApplication, QWidget
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import QRect
class QExampleLabel (QLabel):
def __init__(self, parentQWidget = None):
super(QExampleLabel, self).__init__(parentQWidget)
self.initUI()
def initUI (self):
self.setPixmap(QPixmap('input.png'))
def mousePressEvent (self, eventQMouseEvent):
self.originQPoint = eventQMouseEvent.pos()
self.currentQRubberBand = QRubberBand(QRubberBand.Rectangle, self)
self.currentQRubberBand.setGeometry(QRect(self.originQPoint, QtCore.QSize()))
self.currentQRubberBand.show()
def mouseMoveEvent (self, eventQMouseEvent):
self.currentQRubberBand.setGeometry(QRect(self.originQPoint, eventQMouseEvent.pos()).normalized())
def mouseReleaseEvent (self, eventQMouseEvent):
self.currentQRubberBand.hide()
currentQRect = self.currentQRubberBand.geometry()
self.currentQRubberBand.deleteLater()
cropQPixmap = self.pixmap().copy(currentQRect)
cropQPixmap.save('output.png')
if __name__ == '__main__':
myQApplication = QApplication(sys.argv)
myQExampleLabel = QExampleLabel()
myQExampleLabel.show()
sys.exit(myQApplication.exec_())

Background picture in QMainwindow PyQt5

I'm trying to get a background image to my mainwindow but i can't get it to work properly.
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QLabel
from PyQt5.QtGui import QIcon
from PyQt5 import QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtSvg import *
from PyQt5.QtWidgets import *
from abc import abstractmethod
class App(QMainWindow):
def __init__(self, parent=None):
super(App, self).__init__(parent=parent)
self.title = 'Title'
self.left = 500
self.top = 500
self.width = 440
self.height = 280
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# ...
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
#view = TableScene(ex)
ex.show()
sys.exit(app.exec_())
I've tried different kinds of methods but none of them works as it should.
I found the following code as a solution from another topic but it just gives me a black background and the rest of the widgets get laggy.
oImage = QImage("table.png")
sImage = oImage.scaled(QSize(440, 280))
palette = QPalette()
palette.setBrush(QPalette.Window, QBrush(sImage))
self.setPalette(palette)
I don't know if the whole window gets laggy or what really happens but the picture below is a screenshot of a part of the window using the code above, and as you can see it gets all black and the slider shows all the previous position it has been on, sort of laggy anyways.
I've also tried the setStyleSheet but I don't know if it's my syntax that's wrong or if it's a faulty way of doing it. Does anyone know a way of doing it correctly?
EDIT
This is my current window:
This is the picture I'm trying to implement as a background to my current window, the picture called "table.png" :
This is a visualization of what I'm trying to do, and this is made in paint since I don't know how to do it correctly:
And this is what I get if i use the code from the other topic:
One of the possible reasons why a black background appears is that QImage is null. And a QImage is null because the image is invalid or because the image path is incorrect. In this case I think it is the second case since the OP uses a relative path that is prone to errors. The solution is to build the absolute path using the script information such as its location:
import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
class App(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(App, self).__init__(parent=parent)
self.initUI()
def initUI(self):
self.setWindowTitle("Title")
self.setGeometry(500, 500, 440, 280)
oImage = QtGui.QImage(os.path.join(CURRENT_DIR, "table.png"))
sImage = oImage.scaled(QtCore.QSize(440, 280))
palette = QtGui.QPalette()
palette.setBrush(QtGui.QPalette.Window, QtGui.QBrush(sImage))
self.setPalette(palette)
pushbutton = QtWidgets.QPushButton("test", self)
pushbutton.move(100, 100)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
ex = App()
ex.show()
sys.exit(app.exec_())
Note: The image provided by the OP has extension .jpg but the one indicated by code is .png, maybe "imgur" has changed the extension.
Note: If the window is resized manually, the following behavior will be observed:
So for this there are 2 possible solutions depending on the developer's criteria:
Set a fixed size: self.setFixedSize(440, 280)
Adapt the image to the size of the window:
import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
class App(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(App, self).__init__(parent=parent)
self.initUI()
def initUI(self):
self.setWindowTitle("Title")
self.setGeometry(500, 500, 440, 280)
pushbutton = QtWidgets.QPushButton("test", self)
pushbutton.move(100, 100)
self.oImage = QtGui.QImage(os.path.join(CURRENT_DIR, "table.png"))
# or QPixmap
# self.oPixmap = QtGui.QPixmap(os.path.join(CURRENT_DIR, "table.png"))
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.drawImage(self.rect(), self.oImage)
# or QPixmap
# painter.drawPixmap(self.rect(), self.oPixmap)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
ex = App()
ex.show()
sys.exit(app.exec_())
or
import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
class App(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(App, self).__init__(parent=parent)
self.initUI()
def initUI(self):
self.setWindowTitle("Title")
self.setGeometry(500, 500, 440, 280)
pushbutton = QtWidgets.QPushButton("test", self)
pushbutton.move(100, 100)
self.setStyleSheet(
"""
QMainWindow{
border-image: url(%s) 0 0 0 0 stretch stretch
}
"""
% os.path.join(CURRENT_DIR, "table.png")
)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
ex = App()
ex.show()
sys.exit(app.exec_())

Line Animation with QPropertyAnimation

Trying to animate a line growing from nothing to a (0,0) to (200, 200) line with PyQt5 and using QPropertyAnimation. I already read a lot of documentation about Qt and tried several samples, but I just cannot get this to work. This is the code I have now:
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QPainter, QPixmap, QPainterPath
from PyQt5.QtCore import QObject, QPointF, QPropertyAnimation, pyqtProperty
from PyQt5.QtCore import QLineF
import sys
class Sample(QWidget):
l1 = QLineF(QPointF(), QPointF())
def __init__(self):
super().__init__()
self.initView()
self.initAnimation()
def initView(self):
self.show()
def initAnimation(self):
self.anim = QPropertyAnimation(self.l1, b'geometry')
self.anim.setDuration(7000)
self.anim.setStartValue(QPointF(0, 0))
self.anim.setEndValue(QPointF(200, 200))
self.anim.start()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Sample()
sys.exit(app.exec_())
Not posting all previous attemps, each one fails with a different error. I got a fade out animation on a widget to work, and a picture following a path, but I can seem to make a simple line drawing work. I was hoping to achieve something like this:
Codepen example
Qt documentation is huge and it seems there are several ways to achieve this, painter and timer, animation, variant animation, but I am not very familiar with C++ and the translation to Python is not always easy. Also samples are not that easy to find.
Am I missing something obvious?
Thanks!
For the record, this is what I achieved so far but as soon as I un-comment the QPropertyAnimation creation, app does not launch. Anyway I was still far from the result in the accepted answer.
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
class MyLine(QGraphicsLineItem, QObject):
def __init__(self):
super().__init__()
def _set_start(self, point):
self.setLine(point.x(), point.y(), self.line().p2().x(), self.line().p2().y())
def _set_end(self, point):
self.setLine(self.line().p1().x(), self.line().p1().y(), point.x(), point.y())
start = pyqtProperty(QPointF, fset=_set_start)
end = pyqtProperty(QPointF, fset=_set_end)
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
hbox = QHBoxLayout(self)
self.button = QPushButton("Start", self)
self.button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
hbox.addWidget(self.button)
hbox.addSpacing(40)
self.line = MyLine()
self.line.setLine(0, 0, 10, 10)
scene = QGraphicsScene()
scene.addItem(self.line)
view = QGraphicsView(scene)
hbox.addWidget(view)
self.anim = QPropertyAnimation(self.line, b"end") # crash without error here
# self.anim.setDuration(2500)
# self.anim.setLoopCount(1)
# self.anim.setStartValue(QPointF(10, 10))
# self.anim.setEndValue(QPointF(200, 200))
# self.button.clicked.connect(self.anim.start)
self.setGeometry(300, 300, 380, 250)
self.setWindowTitle('Color anim')
self.show()
if __name__ == "__main__":
app = QApplication([])
ex = Example()
ex.show()
app.exec_()
You have to use QGraphicsView, QGraphicsScene with QGraphicsLineItem as I show below:
from PyQt5 import QtCore, QtGui, QtWidgets
class LineAnimation(QtCore.QObject):
def __init__(self, parent=None):
super(LineAnimation, self).__init__(parent)
self.m_line = QtCore.QLineF()
self.m_item = QtWidgets.QGraphicsLineItem()
self.m_item.setLine(self.m_line)
self.m_item.setPen(
QtGui.QPen(
QtGui.QColor("salmon"),
10,
QtCore.Qt.SolidLine,
QtCore.Qt.SquareCap,
QtCore.Qt.RoundJoin,
)
)
self.m_animation = QtCore.QPropertyAnimation(
self,
b"p2",
parent=self,
startValue=QtCore.QPointF(0, 0),
endValue=QtCore.QPointF(200, 200),
duration=5 * 1000,
)
self.m_animation.start()
def p1(self):
return self.m_line.p1()
def setP1(self, p1):
self.m_line.setP1(p1)
self.m_item.setLine(self.m_line)
def p2(self):
return self.m_line.p2()
def setP2(self, p2):
self.m_line.setP2(p2)
self.m_item.setLine(self.m_line)
p1 = QtCore.pyqtProperty(QtCore.QPointF, fget=p1, fset=setP1)
p2 = QtCore.pyqtProperty(QtCore.QPointF, fget=p2, fset=setP2)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
scene = QtWidgets.QGraphicsScene(self)
view = QtWidgets.QGraphicsView(
scene, alignment=QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop
)
self.setCentralWidget(view)
line_animation = LineAnimation(self)
scene.addItem(line_animation.m_item)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())

PYQT Background image not showing correctly

I created a file using QT Designer, and I uploaded a background image. This file works well and the image appears in the background.
However, when the file is import to the main file, the image does not appear in the background correctly.
and project link
https://github.com/ahmedlam3y/GarageSystem
Because it is not the main window, but it is Ù‹Widget so the picture was not visible in the background and one of the Widgets has been set to the mainWindow so it work correctly
and The code for solution:
import sys
from PyQt5.QtCore import QSize
from PyQt5 import QtCore, QtGui, QtWidgets as Q
from PyQt5.QtGui import QImage, QPalette, QBrush
from PyQt5.QtWidgets import *
import image_rc
from SignIN import Ui_Form as SignInForm
from WelFrame import Ui_Form as WelFrameForm
from SignUp import Ui_Form as SignUpForm
from Accounting import Ui_Form as AccountForm
class SignIn(Q.QWidget, SignInForm): # Widget
def __init__(self, parent=None):
super(SignIn, self).__init__(parent)
Q.QWidget.__init__(self, parent)
self.setupUi(self)
oImage = QImage("GTR.png")
sImage = oImage.scaled(QSize(600, 360)) # resize Image to widgets size
palette = QPalette()
palette.setBrush(10, QBrush(sImage)) # 10 = WindowRole
self.setPalette(palette)
class WelFrame(Q.QMainWindow, WelFrameForm): # MainWindow
def __init__(self, parent=None):
Q.QWidget.__init__(self, parent)
self.setupUi(self)
class SignUp(Q.QWidget, SignUpForm): # Widget
def __init__(self, parent=None):
Q.QWidget.__init__(self, parent)
self.setupUi(self)
oImage = QImage("GTR.png")
sImage = oImage.scaled(QSize(600, 360)) # resize Image to widgets size
palette = QPalette()
palette.setBrush(10, QBrush(sImage)) # 10 = WindowRole
self.setPalette(palette)
class Accout(Q.QWidget, AccountForm): # Widget
def __init__(self, parent=None):
Q.QWidget.__init__(self, parent)
self.setupUi(self)
oImage = QImage("GTR.png")
sImage = oImage.scaled(QSize(600, 360)) # resize Image to widgets size
palette = QPalette()
palette.setBrush(10, QBrush(sImage)) # 10 = WindowRole
self.setPalette(palette)
def foo(w1, w2):
w1.show()
w2.hide()
if __name__ == '__main__':
app = Q.QApplication(sys.argv)
wel = WelFrame()
signIn = SignIn()
signUp = SignUp()
accout = AccountForm()
wel.pushButton_2.clicked.connect(lambda: foo(signIn, wel))
wel.pushButton.clicked.connect(lambda: foo(signUp, wel))
signIn.pushButton_2.clicked.connect(lambda: foo(wel, signIn))
signUp.pushButton_2.clicked.connect(lambda: foo(wel, signUp))
wel.show()
sys.exit(app.exec_())

In PyQt, image won't show after override mousePressEvent of QGraphicsView

I want to write a simple program shows a picture and print which pixel was clicked by override mousePressEvent of QGraphicsView.
When I don't override mousePressEvent of QGraphicsView, the image shows fine. But when I do override it, not only the position failed to show itself, the canvas become blank.
before override:
import sys
from PyQt5 import Qt
from PyQt5 import uic
a = Qt.QApplication(sys.argv)
from untitled import Ui_Form
# class override_graphicsView (Qt.QGraphicsView):
#
# def mousePressEvent(self, event):
# print(event.pos())
class Image_Process(Qt.QWidget):
def __init__(self):
super(Image_Process, self).__init__()
self.path = r"d:\test\winxp.jpg" #image path
self.new = Ui_Form()
self.new.setupUi(self)
# self.new.graphicsView = override_graphicsView()
self.pixmap = Qt.QPixmap()
self.pixmap.load(self.path)
self.pixmap = self.pixmap.scaled(self.size(), Qt.Qt.KeepAspectRatio)
self.graphicsPixmapItem = Qt.QGraphicsPixmapItem(self.pixmap)
self.graphicsScene = Qt.QGraphicsScene()
self.graphicsScene.addItem(self.graphicsPixmapItem)
self.new.graphicsView.setScene(self.graphicsScene)
my_Qt_Program = Image_Process()
my_Qt_Program.show()
sys.exit(a.exec_())
After I uncomment those lines, the canvas becomes this, and nothing was printed after click.
The untitled.py was generated from QtDesigner
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created: Mon Jan 12 02:07:05 2015
# by: PyQt5 UI code generator 5.3.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(451, 286)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Form.sizePolicy().hasHeightForWidth())
Form.setSizePolicy(sizePolicy)
self.gridLayout = QtWidgets.QGridLayout(Form)
self.gridLayout.setObjectName("gridLayout")
self.graphicsView = QtWidgets.QGraphicsView(Form)
self.graphicsView.setObjectName("graphicsView")
self.gridLayout.addWidget(self.graphicsView, 0, 0, 1, 1)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
Helped by Plouff, I have solved my own problem.
First, I should override QGraphicsScene instead of QGraphicsView, and the following line should be called for QGraphicsScene to handle mousePressEvent
super(override_graphicsScene, self).mousePressEvent(event)
Modified code:
import sys
from PyQt5 import Qt
from PyQt5 import uic
a = Qt.QApplication(sys.argv)
from untitled import Ui_Form
# Override like this:
class override_graphicsScene (Qt.QGraphicsScene):
def __init__(self,parent = None):
super(override_graphicsScene,self).__init__(parent)
def mousePressEvent(self, event):
super(override_graphicsScene, self).mousePressEvent(event)
print(event.pos())
class Image_Process(Qt.QWidget):
def __init__(self):
super(Image_Process, self).__init__()
self.path = r"d:\test\winxp.jpg" #image path
self.new = Ui_Form()
self.new.setupUi(self)
self.pixmap = Qt.QPixmap()
self.pixmap.load(self.path)
self.pixmap = self.pixmap.scaled(self.size(), Qt.Qt.KeepAspectRatio)
self.graphicsPixmapItem = Qt.QGraphicsPixmapItem(self.pixmap)
self.graphicsScene = override_graphicsScene(self)
self.graphicsScene.addItem(self.graphicsPixmapItem)
self.new.graphicsView.setScene(self.graphicsScene)
my_Qt_Program = Image_Process()
my_Qt_Program.show()
sys.exit(a.exec_())
The program works fine.

Categories

Resources