如何使QPushButton成为加载按钮?

时间:2018-12-04 18:04:01

标签: python pyqt pyqt5 qpushbutton

有没有办法从QPushButton中制作一个加载按钮?我想在Qt中做类似https://coreui.io/docs/components/loading-buttons/的事情。这可能吗?

我想从每个列表小部件中创建一个加载/进度栏,如下所示。

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以使用QMovie加载gif并将其设置为QPushButton中的图标,在以下示例中,实现分别开始和结束动画的start和stop方法以及传递gif路径的setGif方法:

from PyQt5 import QtCore, QtGui, QtWidgets

class LoadingButton(QtWidgets.QPushButton):
    @QtCore.pyqtSlot()
    def start(self):
        if hasattr(self, "_movie"):
            self._movie.start()

    @QtCore.pyqtSlot()
    def stop(self):
        if hasattr(self, "_movie"):
            self._movie.stop()
            self.setIcon(QtGui.QIcon())

    def setGif(self, filename):
        if not hasattr(self, "_movie"):
            self._movie = QtGui.QMovie(self)
            self._movie.setFileName(filename)
            self._movie.frameChanged.connect(self.on_frameChanged)
            if self._movie.loopCount() != -1:
                self._movie.finished.connect(self.start)
        self.stop()

    @QtCore.pyqtSlot(int)
    def on_frameChanged(self, frameNumber):
        self.setIcon(QtGui.QIcon(self._movie.currentPixmap()))

if __name__ == '__main__':
    import sys
    import random
    app = QtWidgets.QApplication(sys.argv)
    w = QtWidgets.QWidget()
    lay = QtWidgets.QVBoxLayout(w)
    for i in range(5):
        button = LoadingButton("Install")
        button.setGif("loading.gif")
        QtCore.QTimer.singleShot(random.randint(3000, 6000), button.start)
        QtCore.QTimer.singleShot(random.randint(8000, 12000), button.stop)
        lay.addWidget(button)
    w.show()
    sys.exit(app.exec_())

loading.gif

enter image description here

enter image description here