简体   繁体   English

PyQt5-如何在QMainWindow类中显示图像?

[英]PyQt5 - How to display image in QMainWindow class?

I'm trying to display a picture in a QMainWindow class: 我正在尝试在QMainWindow类中显示图片:

from PyQt5.QtWidgets import QLabel, QMainWindow, QApplication
from PyQt5.QtGui import QPixmap
import sys


class Menu(QMainWindow):

    def __init__(self):
        super().__init__()
        self.setWindowTitle("Title")
        label = QLabel(self)
        pixmap = QPixmap('capture.png')
        label.setPixmap(pixmap)
        self.resize(pixmap.width(), pixmap.height())
        self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Menu()
    sys.exit(app.exec_())

But it doesn't show the image, just opens the window. 但是它不显示图像,只是打开窗口。 I'm insisting on a QMainWindow class because I'm trying to write something like a paint app, so I'll be able to write a menu, and I'll be able to write on the picture. 我坚持使用QMainWindow类,因为我试图编写类似绘画应用程序之类的东西,因此我将能够编写菜单,并且能够在图片上书写。

Any suggestions would be appreciated. 任何建议,将不胜感激。

Thanks. 谢谢。

QMainWindow.setCentralWidget(widget) QMainWindow.setCentralWidget(部件)

Sets the given widget to be the main window's central widget. 将给定的小部件设置为主窗口的中央小部件。

from PyQt5.QtWidgets import QLabel, QMainWindow, QApplication, QWidget, QVBoxLayout
from PyQt5.QtGui import QPixmap
import sys


class Menu(QMainWindow):

    def __init__(self):
        super().__init__()
        self.setWindowTitle("Title")

        self.central_widget = QWidget()               
        self.setCentralWidget(self.central_widget)    
        lay = QVBoxLayout(self.central_widget)

        label = QLabel(self)
        pixmap = QPixmap('logo.png')
        label.setPixmap(pixmap)
        self.resize(pixmap.width(), pixmap.height())

        lay.addWidget(label)
        self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Menu()
    sys.exit(app.exec_())

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM