4

Is there a way to make a loading button out of a QPushButton? I want to do something like https://coreui.io/docs/components/loading-buttons/ but in Qt. Is this possible?

I would like to make a loading/progress bar out of each list widget item like below.

enter image description here

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
spitfiredd
  • 2,897
  • 5
  • 32
  • 75

1 Answers1

7

You can use QMovie to load a gif and set it as an icon in a QPushButton, in the following example implement the start and stop method that starts and ends the animation, respectively, and the setGif method that passes the gif path:

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

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Is there any way to change gifs? for example, if I just loaded the app it should show one gif and if i clicked the button it should show another. – Ben Aug 16 '23 at 15:46