如何每隔指定的秒数更改PyQt4窗口背景图像

时间:2016-08-10 17:16:53

标签: python pyqt pyqt4

我想知道如何为我的PyQt4窗口设置背景图像,然后每隔5秒更改一次。

1 个答案:

答案 0 :(得分:1)

这是一个实现你想要的小例子:

from PyQt4 import QtGui, QtCore
import sys
import os
from distutils.sysconfig import get_python_lib


class Example(QtGui.QMainWindow):

    def __init__(self, path_list):
        super(Example, self).__init__()
        self.init_ui(path_list)

    def init_ui(self, path_list):
        self.palette = QtGui.QPalette()
        self.setWindowTitle("PyQt test")
        self.resize(800, 600)

        self.load_list_backgrounds(path_list)
        self.change_background()

        self.timer = QtCore.QTimer(self)
        self.timer.setInterval(5000)
        self.timer.timeout.connect(self.change_background)
        self.timer.start()

        self.show()

    def load_list_backgrounds(self, path_list):
        self.list_pixmaps = [QtGui.QPixmap(p) for p in path_list]
        self.list_brushes = [QtGui.QBrush(l.scaled(self.size(), QtCore.Qt.IgnoreAspectRatio))
                             for l in self.list_pixmaps]

        self.index_image = 0

    def change_background(self):
        print 'tick'
        self.palette.setBrush(
            QtGui.QPalette.Background, self.list_brushes[self.index_image % len(self.list_brushes)])
        self.setPalette(self.palette)
        self.index_image += 1


def main():
    app = QtGui.QApplication(sys.argv)
    QtCore.QCoreApplication.addLibraryPath(
        os.path.join(get_python_lib(), "PyQt4", "plugins"))
    print QtGui.QImageReader.supportedImageFormats()

    home_path = os.path.expanduser('~')
    ex = Example([
        os.path.join(home_path, 'Desktop', 'test.jpg'),
        os.path.join(home_path, 'Desktop', 'test1.jpg'),
        os.path.join(home_path, 'Desktop', 'test2.jpg')
    ])

    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

需要考虑的几点注意事项:

  • 也许您不需要手动添加pyqt插件路径
  • 根据QMainWindow的大小调整画笔,如果不是您想要的,请查看docs of the scaled method