So I have this Ui_MainWindow class generated by pyuic5.
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'MainWindow.ui'
#
# Created by: PyQt5 UI code generator 5.9
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 450)
self.centralWidget = QtWidgets.QWidget(MainWindow)
self.centralWidget.setObjectName("centralWidget")
self.canvas = QtWidgets.QWidget(self.centralWidget)
self.canvas.setGeometry(QtCore.QRect(70, 30, 621, 341))
self.canvas.setAutoFillBackground(False)
self.canvas.setObjectName("canvas")
self.gview = QtWidgets.QGraphicsView(self.canvas)
self.gview.setGeometry(QtCore.QRect(80, 50, 256, 192))
self.gview.setObjectName("gview")
MainWindow.setCentralWidget(self.centralWidget)
self.menuBar = QtWidgets.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 800, 22))
self.menuBar.setObjectName("menuBar")
self.menuhola = QtWidgets.QMenu(self.menuBar)
self.menuhola.setObjectName("menuhola")
self.menust = QtWidgets.QMenu(self.menuBar)
self.menust.setObjectName("menust")
MainWindow.setMenuBar(self.menuBar)
self.menuBar.addAction(self.menuhola.menuAction())
self.menuBar.addAction(self.menust.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.menuhola.setTitle(_translate("MainWindow", "hola"))
self.menust.setTitle(_translate("MainWindow", "splendid"))
And I want to paint on something, as long as it's not the main window. However, no matter what I try, it just doesn't work.
Here's my code:
import sys
from PyQt5 import QtWidgets
from PyQt5.QtGui import QPainter
from src.qt_design.main_window import Ui_MainWindow
class SystemApp(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
def paintEvent(self, event):
# Nope
painter = QPainter(self.ui.gview)
painter.drawLine(0, 0, 50, 50)
# Nope
painter = QPainter(self.ui.canvas)
painter.drawLine(0, 0, 50, 50)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = SystemApp()
window.show()
sys.exit(app.exec_())
I'm not sure if I should either:
1. Paint with this parent on its children (like what I tried above)
2. Override children's paintEvent, but it's maybe a bad idea, see here
Any help will be appreciated!
You can get what you are trying to accomplish with an event filter
class SystemApp(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.gview.installEventFilter(self)
self.ui.canvas.installEventFilter(self)
def eventFilter(self, obj, e):
if e.type() == QtCore.QEvent.Paint:
painter = QPainter()
painter.begin(obj)
if obj == self.ui.canvas:
painter.setPen(QtCore.Qt.red) # Some specific painting
painter.drawLine(0, 0, 50, 50)
painter.end()
return True
return super().eventFilter(obj, e)
Related
I want to display an image using QGraphicsView in a window. I have a basic QGraphicsView and a button based test.ui file generated from QtDesigner tool. Corresponding test.py file:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'test.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(640, 480)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName("verticalLayout")
self.graphicsView = QtWidgets.QGraphicsView(self.centralwidget)
self.graphicsView.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.graphicsView.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.graphicsView.setObjectName("graphicsView")
self.verticalLayout.addWidget(self.graphicsView)
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setObjectName("pushButton")
self.verticalLayout.addWidget(self.pushButton)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 640, 26))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
I made use of QGraphicsScene to display an image inside this QGraphicsView. My current working solution is to mess up the above .py file as follows:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'test.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(640, 480)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName("verticalLayout")
self.scene = QtWidgets.QGraphicsScene(self.centralwidget) #added
self.graphicsView = QtWidgets.QGraphicsView(self.scene) #edited
self.graphicsView.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.graphicsView.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.graphicsView.setObjectName("graphicsView")
self.verticalLayout.addWidget(self.graphicsView)
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setObjectName("pushButton")
self.verticalLayout.addWidget(self.pushButton)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 640, 26))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
self.pushButton.clicked.connect(self.display)
def display(self):
import imageio, numpy
self.scene.clear()
input_image = imageio.imread('image.jpg').copy()
height, width, channels = input_image.shape
bytesPerLine = channels * width
qimg = QtGui.QImage(input_image, width, height, bytesPerLine, QtGui.QImage.Format_RGB888)
self.pixmap = QtGui.QPixmap.fromImage(qimg)
self.scene.addPixmap(self.pixmap) #add pixmap to scene
self.graphicsView.scale(0.5,0.5)
self.scene.update()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
However, this solution is not systematic. I want to do the same without editing the original test.ui generated test.py file.
So, I tried following code which to me appears like a systematic translation of the previous working code. However, it fails to produce any display on button click:
from PyQt5 import QtCore, QtGui, QtWidgets
from test import Ui_MainWindow
class myWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent=parent)
self.setupUi(self)
self.scene = QtWidgets.QGraphicsScene(self.centralwidget) #append scene method
self.graphicsView = QtWidgets.QGraphicsView(self.scene) #graphicsView re-assigned with scene
self.pushButton.clicked.connect(self.display)
def display(self):
import imageio, numpy
self.scene.clear()
input_image = imageio.imread('image.jpg').copy()
height, width, channels = input_image.shape
bytesPerLine = channels * width
qimg = QtGui.QImage(input_image, width, height, bytesPerLine, QtGui.QImage.Format_RGB888)
self.pixmap = QtGui.QPixmap.fromImage(qimg)
self.scene.addPixmap(self.pixmap) #add pixmap to scene
self.graphicsView.scale(0.5,0.5)
self.scene.update()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = myWindow()
w.show()
sys.exit(app.exec_())
I am likely messing up something due to my limited understanding of class inheritance, QGraphicsView, and QGraphicsScene. Any pointers to my mistakes would be very helpful.
Note: I am using a myWindow class to integrate some key press functionality in future. I think the issue is more to do with how to selectively append/redefine few lines inside a parent class function. Is this even possible without re-writing the whole setupUi method? Or, is there another smarter way to perform the same task?
You have to set the scene to the existing QGraphicsView instead of creating a new QGraphicsView:
class myWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.scene = QtWidgets.QGraphicsScene(self.centralwidget)
self.graphicsView.setScene(self.scene)
self.pushButton.clicked.connect(self.display)
def display(self):
# ...
This is a sample code with just a push button and a textedit, i need to write line x line using a loop in a textedit when button is clicked.
The problem is that i need to implement threads because without them the program crashes or it doesn't write line x line, but all together when the loop ends;
and i need to implement in my application a textedit that shows info while the program loads "something".
So my question is, how to rewrite this code using threads to write in textedit when button is clicked?
The method i should run when the button is clicked is "write"
it should work like a print inside a for loop , it would print not all at once
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(640, 480)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
self.textEdit.setGeometry(QtCore.QRect(150, 220, 321, 71))
self.textEdit.setObjectName("textEdit")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(240, 100, 75, 23))
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 640, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
self.pushButton.clicked.connect(self.write)
def write(self):
string=""
for i in range(1000):
string="\n"+str(i)
self.textEdit.insertPlainText(string)
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
First of all it is recommended not to modify the class generated by Qt Designer so you must regenerate the file and assume that it is called mainwindow.py: pyuic5 your_file.ui -o mainwindow.py -x.
Considering the above, the logic is to generate the information in another thread and send it to the GUI to modify it:
main.py
import threading
from PyQt5 import QtCore, QtGui, QtWidgets
from mainwindow import Ui_MainWindow
class WriterWorker(QtCore.QObject):
textChanged = QtCore.pyqtSignal(str)
def start(self):
threading.Thread(target=self._execute, daemon=True).start()
def _execute(self):
string = ""
for i in range(1000):
string = "\n"+str(i)
self.textChanged.emit(string)
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.writer_worker = WriterWorker()
self.writer_worker.textChanged.connect(self.on_text_changed)
self.pushButton.clicked.connect(self.writer_worker.start)
#QtCore.pyqtSlot(str)
def on_text_changed(self, text):
self.textEdit.insertPlainText(text)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
I'm facing the problem with Threads. I'm displaying current CPU usage with progress bar and it seems to be working well but the performance of whole window is terrible. Can't even click the button without laggy behavior. Is there any simple solution to fix it?
Here is my main code
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QThread, pyqtSignal
import progressBarUI
import sys
import sysnfo
class MainWindow(QtWidgets.QMainWindow, progressBarUI.Ui_MainWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.threadclass = ThreadClass()
self.threadclass.start()
self.threadclass.signal.connect(self.updateProgressBar)
def updateProgressBar(self):
current_percentage = sysnfo.getCpuPercentage()
self.progressBar.setValue(current_percentage)
class ThreadClass(QThread):
signal = pyqtSignal(int)
def __init__(self, parent=None):
super(ThreadClass, self).__init__(parent)
def run(self):
while True:
current_percentage = sysnfo.getCpuPercentage()
self.signal.emit(current_percentage)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainAppWin = MainWindow()
mainAppWin.show()
app.exec_()
Here is sysnfo module:
import psutil as ps
def getCpuPercentage():
return ps.cpu_percent(interval=1)
And UI file (converted to .py file):
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(787, 203)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.progressBar = QtWidgets.QProgressBar(self.centralwidget)
self.progressBar.setGeometry(QtCore.QRect(370, 20, 381, 111))
self.progressBar.setProperty("value", 0)
self.progressBar.setObjectName("progressBar")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(20, 50, 151, 41))
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 787, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "Click me"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
When you use the "interval" parameter you are indicating that it measures the information during that time and calculates the average causing the execution of that function to take "interval" seconds, and the correct thing is to execute it in another thread, but you make the mistake of executing it too in the updateProgressBar method that lives in the main thread blocking it, instead use the information that sends you the signal:
#QtCore.pyqtSlot(int)
def updateProgressBar(self, percentage):
self.progressBar.setValue(percentage)
I'm making a simple PyQt5 application and am curious about how to make the circle move with the arrow keys. I want it to move 5 pixels on every press.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(500, 500)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.coords = QtWidgets.QPushButton(self.centralwidget)
self.coords.setGeometry(QtCore.QRect(0, 0, 75, 23))
self.coords.setObjectName("coords")
self.mover = QtWidgets.QLabel(self.centralwidget)
self.mover.setGeometry(QtCore.QRect(200, 200, 50, 50))
self.mover.setText("")
self.mover.setPixmap(QtGui.QPixmap("mover.png"))
self.mover.setObjectName("mover")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 500, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "DYM"))
self.coords.setText(_translate("MainWindow", "Coords"))
if __name__ == "__main__":
# Snip
You shouldn't edit nor use the code provided by pyuic from Designer files directly.
Instead, you have to create your own code that uses that code as explained here.
A very simple and limited implementation (which doesn't use Designer .ui files) looks like this:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Mover(QtWidgets.QLabel):
def __init__(self, parent=None):
super().__init__(parent)
self.setGeometry(0, 0, 500, 21)
self.setPixmap(QtGui.QPixmap('mover.png'))
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Up:
self.move(self.x(), self.y() - 5)
elif event.key() == QtCore.Qt.Key_Down:
self.move(self.x(), self.y() + 5)
elif event.key() == QtCore.Qt.Key_Left:
self.move(self.x() - 5, self.y())
elif event.key() == QtCore.Qt.Key_Right:
self.move(self.x() + 5, self.y())
else:
QtWidgets.QLabel.keyPressEvent(self, event)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
centralWidget = QtWidgets.QWidget()
self.setCentralWidget(centralWidget)
self.mover = Mover(centralWidget)
self.mover.setFocus()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
There are some drawback about this, though: I had to setFocus to the widget in order to make it capture key press events, which means that if you have any other widget that interacts with key events (such as a QLineEdit) and it gets focus, your "mover" widget won't move anymore until it receives its focus back (which is usually achieved by means of a QWidget.setFocusPolicy()).
I'm pretty new to PYQT5 and I wanted to draw a circle on a Pixmap that is contained in a QLabel in the MainWindow UI on PYQT5 with this code:
from PyQt5 import QtCore, QtGui, QtWidgets
background_image_path = '001_01_01_041_05.png'
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(60, 60, 331, 401))
self.label.setObjectName("label")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 28))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self._image = QtGui.QPixmap(background_image_path)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setPixmap(self._image)
def paintEvent(self, event):
painter = QtGui.QPainter(self._image)
painter.drawPixmap(self.rect(), self._image)
pen = QtGui.QPen()
pen.setWidth(5)
painter.setPen(pen)
painter.drawEllipse(300, 300, 70, 70)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
However, I cannot get the paintEvent(self, event) function to get called. When I did get to call paintEvent(self, event), I could not see the circle being drawn onto the pixmap. I tried setting the QPainter to the Pixmap itself (in painter = QtGui.QPainter(self._image)), but that did not work either.
What did I do incorrectly?
The code below works, which is what my code is based on:
from PyQt5 import QtWidgets, QtGui, QtCore
background_image_path = '001_01_01_041_05.png'
class ImageScroller(QtWidgets.QWidget):
def __init__(self):
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.drawPixmap(self.rect(), self._image)
pen = QtGui.QPen()
pen.setWidth(5)
painter.setPen(pen)
painter.drawEllipse(300, 300, 70, 70)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = ImageScroller()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
Any thoughts or advice would be greatly appreciated!
You missed a couple of lines.
Try it:
from PyQt5 import QtWidgets, QtGui, QtCore
background_image_path = 'E:/_Qt/img/heart.png' # '001_01_01_041_05.png'
class ImageScroller(QtWidgets.QWidget):
def __init__(self):
super().__init__() # <-------
self._image = QtGui.QPixmap(background_image_path) # <-------
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.drawPixmap(self.rect(), self._image)
pen = QtGui.QPen()
pen.setWidth(5)
painter.setPen(pen)
painter.drawEllipse(300, 300, 70, 70)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = ImageScroller()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
The real problem here is that you are editing the module generated by pyuic,
which is always a very bad idea. Try it:
from PyQt5 import QtCore, QtGui, QtWidgets
background_image_path = 'E:/_Qt/img/heart.png'
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(200, 0, 760, 560))
self.label.setObjectName("label")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 28))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
# self._image = QtGui.QPixmap(background_image_path)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
# self.label.setPixmap(self._image)
self.label.setText(_translate("MainWindow",
"""
It is not recommended to modify the design file,
it is appropriate to create another file
to join the logic with the design.
"""))
# def paintEvent(self, event):
# painter = QtGui.QPainter(self._image)
# painter.drawPixmap(self.rect(), self._image)
# pen = QtGui.QPen()
# pen.setWidth(5)
# painter.setPen(pen)
# painter.drawEllipse(300, 300, 70, 70)
class MyApp(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super(MyApp, self).__init__()
self.setupUi(self)
self._image = QtGui.QPixmap(background_image_path)
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.drawPixmap(self.rect(), self._image)
#pen = QtGui.QPen()
#pen.setWidth(5)
#painter.setPen(pen)
painter.setPen(QtGui.QPen(QtCore.Qt.blue, 5))
painter.drawEllipse(350, 350, 70, 70)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
# MainWindow = QtWidgets.QMainWindow()
# ui = Ui_MainWindow()
# ui.setupUi(MainWindow)
# MainWindow.show()
window = MyApp()
window.show()
sys.exit(app.exec_())