我是PyQt5的新手,我找不到任何有关如何在加载的图像上绘制QPainter的答案(QPixmap(“myPic.png”))。我尝试在paintEvent方法中执行它,但它不起作用。如果我想在下面的片段中加载图像的顶部画一条线,我该怎么做呢?
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class Example(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(30, 30, 500, 300)
self.initUI()
def initUI(self):
self.pixmap = QPixmap("myPic.png")
lbl = QLabel(self)
lbl.setPixmap(self.pixmap)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
答案 0 :(得分:8)
使用paintEvent
和QPainter
:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class Example(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(30, 30, 500, 300)
def paintEvent(self, event):
painter = QPainter(self)
pixmap = QPixmap("myPic.png")
painter.drawPixmap(self.rect(), pixmap)
pen = QPen(Qt.red, 3)
painter.setPen(pen)
painter.drawLine(10, 10, self.rect().width() -10 , 10)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
myPic.png
输出: