我是PYQT5的新手,想要在MainWindow UI中使用以下代码在包含在QLabel中的Pixmap上画一个圆形:
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_())
然而,我无法让paintEvent(self, event)函数被调用。当我成功调用paintEvent(self, event)时,我看不到圆形被绘制到pixmap上。我尝试将QPainter设置为Pixmap本身(在painter = QtGui.QPainter(self._image)中),但也没有起作用。
我做错了什么?
下面的代码是可以工作的,这也是我的代码所基于的:
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_())
任何想法或建议都将不胜感激!