PyQt5实现一个简单的ImageViewer(菜单+图像)

时间:2018-12-09 20:44:56

标签: python pyqt pyqt5

我是PyQt的初学者。我想创建带有简单菜单的窗口并带有图像标签。 我搜索了如何创建菜单以及如何在标签中显示图像,但无法将这两件事结合在一起。

菜单代码(图像不显示):

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import cv2


class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        label = QLabel(self)
        pixmap = QPixmap('./liver.bmp')
        label.setPixmap(pixmap)
        self.resize(pixmap.width(), pixmap.height())
        # Create new action
        openAction = QAction(QIcon('open.png'), '&Open', self)
        openAction.setShortcut('Ctrl+O')
        openAction.setStatusTip('Open document')
        openAction.triggered.connect(self.openCall)

        # Create menu bar and add action
        menuBar = self.menuBar()
        fileMenu = menuBar.addMenu('&File')
        fileMenu.addAction(openAction)


    def openCall(self):
        pixmap = QPixmap('./default.png')
        label.setPixmap(pixmap)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mainWin = MainWindow()
    mainWin.show()
    sys.exit( app.exec_() )

screenshot(image doesn't display)

不带显示图像的菜单的代码:

import os
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import cv2


class ImageViewer(QWidget):

    def __init__(self):
        QWidget.__init__(self)
        self.setup_ui()

    def setup_ui(self):
        self.image_label = QLabel()
        self.image_label.setPixmap(QPixmap('./default.png'))

        self.main_layout = QVBoxLayout()  # adding widgets to layot
        self.main_layout.addWidget(self.image_label)

        self.setLayout(self.main_layout)  # set layot


if __name__ == "__main__":
    app = QApplication(sys.argv)
    viewer = ImageViewer()
    viewer.show()
app.exec_()

如何结合这两件事?

1 个答案:

答案 0 :(得分:0)

将self添加到所有label变量中,它可以工作,

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import cv2


class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.label = QLabel(self)
        pixmap = QPixmap('./liver.bmp')
        self.label.setPixmap(pixmap)
        self.resize(pixmap.width(), pixmap.height())
        # Create new action
        openAction = QAction(QIcon('open.png'), '&Open', self)
        openAction.setShortcut('Ctrl+O')
        openAction.setStatusTip('Open document')
        openAction.triggered.connect(self.openCall)

        # Create menu bar and add action
        menuBar = self.menuBar()
        fileMenu = menuBar.addMenu('&File')
        fileMenu.addAction(openAction)


    def openCall(self):
        pixmap = QPixmap('./default.png')
        self.label.setPixmap(pixmap)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mainWin = MainWindow()
    mainWin.show()
    sys.exit( app.exec_() )