如何使 QPushButton 成为加载按钮?

How to make a QPushButton a loading button?

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

我想为每个列表小部件项目制作一个 loading/progress 栏,如下所示。

您可以使用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