【问题标题】:PyQt5 - How to display image in QMainWindow class?PyQt5 - 如何在 QMainWindow 类中显示图像?
【发布时间】:2018-12-28 01:26:36
【问题描述】:

我正在尝试在 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 课程,因为我正在尝试编写类似绘画应用程序的东西,这样我就可以编写菜单,并且可以在图片上写字。

任何建议将不胜感激。

谢谢。

【问题讨论】:

  • 与您的问题无关,但您使用的是什么版本的python?
  • Python 3.6.5 蟒蛇
  • 您是否尝试过使用 jpg 图片?
  • 您误用了QMainWindow。看QMainWindow::setCentralWidget
  • @TheCrystalShip 啊,我明白了,你是在 Unix 系统还是 DOS 下工作?

标签: python python-3.x qt pyqt5 qmainwindow


【解决方案1】:

QMainWindow.setCentralWidget(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_())

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多