Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

qt4 - Showing a .gif animation in QLabel

I would like to show a .gif animation in a QLabel widget, alongside text.

The following code won't work:

self.status_txt = QtGui.QLabel('Loading... <img src="etc/loading.gif">')

as the image won't animate.

I tried achiving it by using a QMovie object:

self.status_txt = QtGui.QLabel("Loading...")
movie = QtGui.QMovie("etc/loading.gif")
self.status_txt.setMovie(movie)
movie.start()

But then I can't put the animation and the text together. Is there a different solution besides using two different labels?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you can add a Layout to the label, and then add another Label with the text to that...

self.status_txt = QtGui.QLabel()
movie = QtGui.QMovie("etc/loading.gif")
self.status_txt.setMovie(movie)
movie.start()
self.status_txt.setLayout(QtGui.QHBoxLayout())
self.status_txt.layout().addWidget(QLabel('Loading...'))

edit:

it's possible if you use your own version of a QLabel and a QPainter to paint the text yourself:

from PyQt4.QtCore import QSize
from PyQt4.QtGui import QApplication, QLabel, QMovie, QPainter, QFontMetrics

class QTextMovieLabel(QLabel):
    def __init__(self, text, fileName):
        QLabel.__init__(self)
        self._text = text
        m = QMovie(fileName)
        m.start()
        self.setMovie(m)

    def setMovie(self, movie):
        QLabel.setMovie(self, movie)
        s=movie.currentImage().size()
        self._movieWidth = s.width()
        self._movieHeight = s.height()

    def paintEvent(self, evt):
        QLabel.paintEvent(self, evt)
        p = QPainter(self)
        p.setFont(self.font())
        x = self._movieWidth + 6
        y = (self.height() + p.fontMetrics().xHeight()) / 2
        p.drawText(x, y, self._text)
        p.end()

    def sizeHint(self):
        fm = QFontMetrics(self.font())
        return QSize(self._movieWidth + 6 + fm.width(self._text),
                self._movieHeight)

    def setText(self, text):
        self._text = text

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    l = QTextMovieLabel('Loading...', 'loading.gif')
    l.show()
    app.exec_()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...