将图像显示到qwidget上
要将图像显示到QWidget上,可以使用QPainter类的drawPixmap方法。以下是一个简单的示例代码:
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap, QPainter
from PyQt5.QtWidgets import QWidget, QApplication
class MyWidget(QWidget):
def __init__(self):
super().__init__()
# 创建一个QPixmap对象
self.image = QPixmap('image.jpg')
def paintEvent(self, event):
painter = QPainter(self)
# 将图像绘制到QWidget上
painter.drawPixmap(self.rect(), self.image)
if __name__ == '__main__':
app = QApplication([])
widget = MyWidget()
widget.show()
app.exec_()
在这个例子中,我们创建了一个QPixmap对象,并在paintEvent事件中使用QPainter的drawPixmap方法将其绘制到QWidget上。使用self.rect()来指定绘制的区域为QWidget的整个区域。最后,我们启动了一个QApplication并显示了这个QWidget。
原文地址: https://www.cveoy.top/t/topic/b0WU 著作权归作者所有。请勿转载和采集!