如何在qdialog上显示图像?

时间:2014-11-28 18:10:43

标签: pyqt qwidget qdialog pixmap

请帮助这个代码,因为我真的没有得到这个概念。 我通过点击qwidget上的按钮开始一个对话框。 我还想通过单击对话框上的其他按钮(img_btn)在上述qdialog上显示图像。 我在下面添加了一些代码:

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

class BasicWidget(QWidget):
    def __init__(self, parent=None):
        super(BasicWidget, self).__init__()

        layout = QVBoxLayout()
        self.btn = QPushButton('Show Dialog')
        layout.addWidget(self.btn)
        self.setLayout(layout)
        self.show()

        self.btn.clicked.connect(self.showpic)

    def showpic(self):
        imgshow = PaintPicture()

class PaintPicture(QDialog):
    def __init__(self, parent=None):
        super(PaintPicture, self).__init__()

        layout = QVBoxLayout()
        self.img_btn = QPushButton('Enter')
        layout.addWidget(self.img_btn)

        filename = r'\\some\basic\picture.jpg'
        image = QImage(filename )

        self.imageLabel = QLabel()
        self.imageLabel.setPixmap(QPixmap.fromImage(image))

        layout.addWidget(self.imageLabel)

        self.setLayout(layout)
        self.show()

if __name__ =="__main__":
    app = QApplication(sys.argv)
    widget = BasicWidget()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:0)

首先,您的代码中存在两个错误:

  1. imgshow = PaintPicture()应为self.imgshow = PaintPicture()

  2. 路径对我来说不起作用filename = r'\\some\basic\picture.jpg',但它的工作原理如下:filename = r'./some/basic/picture.jpg'

  3. 现在,如果我理解,你想打开只有“输入”按钮的对话框。当您按下该按钮时,您希望图像显示在同一个对话框的按钮下?如果是这样,这是代码:

    from PyQt4.QtCore import *
    from PyQt4.QtGui import *
    import sys
    
    class BasicWidget(QWidget):
        def __init__(self, parent=None):
            super(BasicWidget, self).__init__()
    
            layout = QVBoxLayout()
            self.btn = QPushButton('Show Dialog')
            layout.addWidget(self.btn)
            self.setLayout(layout)
            self.show()
    
            self.btn.clicked.connect(self.showpic)
    
        def showpic(self):
            self.imgshow = PaintPicture()
    
    class PaintPicture(QDialog):
        def __init__(self, parent=None):
            super(PaintPicture, self).__init__()
    
            layout = QVBoxLayout()
            self.img_btn = QPushButton('Enter')
            self.img_btn.clicked.connect(self.showImage)
            layout.addWidget(self.img_btn)
    
            self.setLayout(layout)
            self.show()
    
        def showImage(self):
            filename = r'./some/basic/picture.jpg'
            image = QImage(filename )
    
            self.imageLabel = QLabel()
            self.imageLabel.setPixmap(QPixmap.fromImage(image))
    
            layout = self.layout()
            layout.addWidget(self.imageLabel)
    
    if __name__ =="__main__":
        app = QApplication(sys.argv)
        widget = BasicWidget()
        sys.exit(app.exec_())