Issue
I'm trying to display an animated GIF on the left side of a QListWidgetItem in a QListWidget with the label text following. I've been reading that QLabels hold QMovies which can run GIF animations and that I'd need to create a custom widget and use that instead of the default QListWidgetItem, but I've had no luck. Does anyone how to do this? Am I over-complicating things?
I've written up a basic test case below:
#! /usr/bin/env python
from PySide2 import QtGui, QtWidgets, QtCore
class List_Widget_Gif(QtWidgets.QWidget):
def __init__(self, label_text, gif, parent=None):
super(List_Widget_Gif, self).__init__(parent)
# Layout
horizontal_box_layout = QtWidgets.QHBoxLayout()
# Create text label
self.text_label = QtWidgets.QLabel()
self.text_label.setText(label_text)
# Create label to apply GIF to (Apparently this is the best thing to use for GIF in this case?)
self.icon_label = QtWidgets.QLabel()
movie = QtGui.QMovie(gif, QtCore.QByteArray(), self)
self.icon_label.setMovie(movie)
movie.start()
# Add widgets to layout
horizontal_box_layout.addWidget(self.text_label)
horizontal_box_layout.addWidget(self.icon_label)
#Set the layout
self.setLayout(horizontal_box_layout)
class TestUI(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(TestUI, self).__init__(parent)
self.setObjectName("TestUI")
#Vars to pass
self.my_gif = "my_cool_animation.gif"
self.my_text = "This is awesome text"
def setup_UI(self):
#Create Default List Widget
list_widget = QtWidgets.QListWidget()
# Create Default List Widget Item
default_list_item = QtWidgets.QListWidgetItem()
# Create Custom List Widget with label and GIF motion
custom_list_widget_item = List_Widget_Gif(self.my_text, self.my_gif)
# Add default item to list widget
list_widget.insertItem(list_widget.count(), default_list_item)
# Set the default item to the custom one with the gif motion.
self.ui.layerList.setItemWidget(default_list_item, custom_list_widget_item)
#Set into UI
self.setCentralWidget(list_widget)
self.show()
if __name__ == "__main__":
app = QtWidgets.QApplication([])
test = TestUI()
test.setup_UI()
app.exec_()
Solution
First you have a typo (it should throw an exception) so you have to change self.ui.layerList
to list_widget
.
Correcting the above there are several possible causes of error:
The margins must be removed from the layout of the custom widget:
horizontal_box_layout.setContentsMargins(0, 0, 0, 0)
Do not use relative paths since they are the cause of silent errors, it is better to build the absolute path based on the location of another element. If I assume that the .gif is in the same folder as the .py then you can use that information to do so it changes:
import os CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
self.my_gif = os.path.join(CURRENT_DIR, "my_cool_animation.gif")
Answered By - eyllanesc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.