【发布时间】:2020-07-12 17:58:53
【问题描述】:
我正在尝试在 QListWidget 中的 QListWidgetItem 左侧显示动画 GIF,并带有以下标签文本。我一直在阅读 QLabels 持有可以运行 GIF 动画的 QMovies,并且我需要创建一个自定义小部件并使用它而不是默认的 QListWidgetItem,但我没有运气。有谁怎么做到这一点?我是不是把事情复杂化了?
我在下面写了一个基本的测试用例:
#! /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_()
【问题讨论】:
-
@DennisJensen 你能详细说明一下吗?对于 UI 类,我只需要使用 super()。如果它们有 def__init__(),PyCharm 甚至让我向我的非 UI 类添加 super ,但我没有理由添加它们。
-
1) 您必须始终如一地使用它,并记录您的使用情况,因为它是您班级外部接口的一部分,无论您喜欢与否。
标签: python python-2.7 pyqt pyside pyside2