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

标签 python python-3.x qt pyqt5 qmainwindow

我正在尝试在 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_())

但它不显示图像,只是打开窗口。我坚持使用 QMainWindow 类,因为我正在尝试编写类似绘画应用程序的东西,这样我就可以编写菜单,并且可以在图片上书写.

如有任何建议,我们将不胜感激。

谢谢。

最佳答案

QMainWindow.setCentralWidget(widget)

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_())

enter image description here

关于python - PyQt5 - 如何在 QMainWindow 类中显示图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51430586/

相关文章:

qt - 如何更改(删除)QListWidget 的选择/事件颜色

c++ - 如何删除选定的图形项目组?

Python:如何使用散点图在 map 上绘制数组?

python - 如何在每次更改日期时重新​​启动的 pandas 中执行累积计算?

python - 在 Python 中非常具体地导入总是一个好主意吗?

python-3.x - 对于 Python 3.8 Azure 数据湖 Gen 2,如何检查文件系统上是否存在文件?

javascript - 如何在 Puppeteer/Pyppeteer 中等待 Recaptcha 加载?

python - 没有名为 PyQt5.sip 的模块

c++ - 重新实现调整大小事件

javascript - 如何在内联字段 Django 中添加属性?