PyQt5-为每个按钮单击打开新图像窗口

时间:2018-07-18 18:11:57

标签: python python-3.x image window pyqt5

我一直在玩PyQt5,被卡在这里。在某个菜单中,对于每个按钮单击(以及给定的numpy图像数组),我正在尝试打开一个新的图像窗口(将numpy数组转换为图像)。

因此,首先,我对一个图像进行了处理(使用this answer将numpy图像数组转换为QPixmap):

NewNumpyImageWindow.py 类:

import cv2
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QPixmap, QImage


class NewImage(QWidget):

    def __init__(self, npImage):
        super().__init__()
        label = QLabel(self)
        pixmap = self.ConvertNumpyToQPixmap(npImage)
        label.setPixmap(pixmap)
        self.resize(pixmap.width(), pixmap.height())
        self.show()

    @staticmethod
    def ConvertNumpyToQPixmap(np_img):
        height, width, channel = np_img.shape
        bytesPerLine = 3 * width
        return QPixmap(QImage(np_img.data, width, height, bytesPerLine, QImage.Format_RGB888).rgbSwapped())


if __name__ == '__main__':
    app = QApplication(sys.argv)
    currentNumpyImage = cv2.imread("capture.png")
    window = NewImage(currentNumpyImage)
    sys.exit(app.exec_())

它工作正常。图像显示为新窗口。 现在,我希望每次按主菜单中的按钮时图像以新窗口显示。

因此,我尝试为每次按下(在“新建”按钮上)创建上述类的实例,但它不起作用。该窗口似乎显示为新窗口,并在代码完成后立即关闭。

NewNumpyImageWindowMenu.py 类:

import cv2
import sys
from PyQt5 import QtWidgets
from NewNumpyImageWindow import NewImage


class Menu(QtWidgets.QMainWindow):

    def __init__(self, numpyPic):
        super().__init__()
        newAct = QtWidgets.QAction('New', self)
        self.numpyPicture = numpyPic
        newAct.triggered.connect(self.newPicture)
        toolbar = self.addToolBar('Exit')
        toolbar.addAction(newAct)
        self.setGeometry(300, 300, 350, 250)
        self.show()

    def newPicture(self):
        NewImage(self.numpyPicture) #From the previous class


if __name__ == '__main__':
    currentNumpyImage = cv2.imread("capture.png")
    app = QtWidgets.QApplication(sys.argv)
    ex = Menu(currentNumpyImage)
    sys.exit(app.exec_())

任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:1)

尝试一下:

NewNumpyImageWindowMenu.py

import cv2
import sys
from PyQt5 import QtWidgets
from NewNumpyImageWindow import NewImage


class Menu(QtWidgets.QMainWindow):

    def __init__(self, numpyPic):
        super().__init__()
        newAct = QtWidgets.QAction('New', self)
        self.numpyPicture = numpyPic
        newAct.triggered.connect(self.newPicture)
        toolbar = self.addToolBar('Exit')
        toolbar.addAction(newAct)
        self.setGeometry(300, 300, 350, 250)
        self.show()

    def newPicture(self):
        #NewImage(self.numpyPicture) #From the previous class  # ---
        self.newImage = NewImage(self.numpyPicture)            # +++


if __name__ == '__main__':
    #currentNumpyImage = cv2.imread("capture.png")
    currentNumpyImage = cv2.imread("logo.png")
    app = QtWidgets.QApplication(sys.argv)
    ex = Menu(currentNumpyImage)
    sys.exit(app.exec_())

enter image description here