1

我有以下代码使用 pyQt 显示图像:

app = QtGui.QApplication(sys.argv)
window = QtGui.QMainWindow()

window.setGeometry(opts.posx, opts.posy, opts.width, opts.height)

pic = QtGui.QLabel(window)
pic.setGeometry(5, 5, opts.width-10, opts.height-10)
pixmap = QtGui.QPixmap(opts.filename)
pixmap = pixmap.scaledToHeight(opts.height)
pic.setPixmap(pixmap)

window.show()
sys.exit(app.exec_())

我想以类的形式包装这段代码,并能够在运行时设置不同的图像,使用信号、套接字、我真的不知道的线程。我会想象这样的事情:

class MyImage(object):
   def __init(self, args):
       some setup code
       self.pic = whatever
   def set_image(self, filename):
       pixmap = QtGui.QPixmap(opts.filename)
       pixmap = pixmap.scaledToHeight(opts.height)
       pic.setPixmap(pixmap)

使用我刚刚调用的原始代码sys.exit(app.exec_()),这使代码“冻结”。但我想从不同的运行 python 代码发送一个信号(和一个文件名)。有什么建议可以轻松直接地处理吗?也许覆盖app.exec_方法?

4

1 回答 1

1

像这样的东西应该适合你:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)

from PyQt4 import QtGui, QtCore

class ImageChanger(QtGui.QWidget):    
    def __init__(self, images, parent=None):
        super(ImageChanger, self).__init__(parent)        

        self.comboBox = QtGui.QComboBox(self)
        self.comboBox.addItems(images)

        self.layout = QtGui.QVBoxLayout(self)
        self.layout.addWidget(self.comboBox)

class MyWindow(QtGui.QWidget):
    def __init__(self, images, parent=None):
        super(MyWindow, self).__init__(parent)
        self.label = QtGui.QLabel(self)

        self.imageChanger = ImageChanger(images)
        self.imageChanger.move(self.imageChanger.pos().y(), self.imageChanger.pos().x() + 100)
        self.imageChanger.show()
        self.imageChanger.comboBox.currentIndexChanged[str].connect(self.changeImage)

        self.layout = QtGui.QVBoxLayout(self)
        self.layout.addWidget(self.label)

    @QtCore.pyqtSlot(str)
    def changeImage(self, pathToImage):
        pixmap = QtGui.QPixmap(pathToImage)
        self.label.setPixmap(pixmap)


if __name__ == "__main__":
    import sys

    images = [  "/path/to/image/1",
                "/path/to/image/2",
                "/path/to/image/3",
                ]

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow(images)
    main.show()

    sys.exit(app.exec_())
于 2013-01-16T21:19:26.593 回答