【问题标题】:how to add color animation to QTreeWidgetItem?如何向 QTreeWidgetItem 添加彩色动画?
【发布时间】:2020-02-15 00:47:10
【问题描述】:

我需要为 QTreeWidgetItem 添加彩色动画,但在我的代码中,它引发了一些错误,谁能帮助我?

代码示例在这里:

class TreeWigetItem(QTreeWidgetItem):
    def __init__(self, parent=None):
        super().__init__(parent)

    @pyqtProperty(QBrush)
    def bcolor(self):
        return self.background(0)

    @bcolor.setter
    def bcolor(self, color):
        self.setBackground(0, color)
        self.setBackground(1, color)

并像这样调用方法:

child_item = TreeWigetItem()
self.child_item_ani = QPropertyAnimation(child_item, b'bcolor')
self.child_item_ani.setDuration(1000)
self.child_item_ani.setEndValue(QBrush(Qt.red))
self.child_item_ani.start()

这里有错误:

self.child_item_ani = QPropertyAnimation(child_item, b'bcolor')  
TypeError: arguments did not match any overloaded call:  
  QPropertyAnimation(parent: QObject = None): argument 1 has unexpected type 'TreeWigetItem'  
  QPropertyAnimation(QObject, Union[QByteArray, bytes, bytearray], parent: QObject = None): argument 1 has unexpected type 'TreeWigetItem'  

【问题讨论】:

    标签: python pyqt pyqt5 qtreewidget qtreewidgetitem


    【解决方案1】:

    Property(PyQt 中的 pyqtProperty) 仅在 QObjects 中有效,但在这种情况下,QTreeWidgetItem 不继承自 QObject,因此 QPropertyAnimation 也不起作用。因此,您应该使用QVariantAnimation,而不是使用QPropertyAnimation,如下所示:

    import os
    from PyQt5 import QtCore, QtGui, QtWidgets
    
    
    class TreeWidgetItem(QtWidgets.QTreeWidgetItem):
        @property
        def animation(self):
            if not hasattr(self, "_animation"):
                self._animation = QtCore.QVariantAnimation()
                self._animation.valueChanged.connect(self._on_value_changed)
            return self._animation
    
        def _on_value_changed(self, color):
            for i in range(self.columnCount()):
                self.setBackground(i, color)
    
    
    if __name__ == "__main__":
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
    
        w = QtWidgets.QTreeWidget(columnCount=2)
    
        it = TreeWidgetItem(["Foo", "Bar"])
    
        # setup animation
        it.animation.setStartValue(QtGui.QColor("white"))
        it.animation.setEndValue(QtGui.QColor("red"))
        it.animation.setDuration(5 * 1000)
        it.animation.start()
    
        # add item to QTreeWidget
        w.addTopLevelItem(it)
    
        w.show()
        sys.exit(app.exec_())
    

    【讨论】:

    • 你的建议工作正常,如果我将我的原始代码更改为class TreeWidgetItem(QTreeWidgetItem, QObject) 以继承 QObject,我认为它也会工作,但我在 cmd 行中运行我的代码,应用程序消失了错误?
    • @jie PyQt 中的多重继承在某些情况下受到限制,QTreeWidgetItem 不在其中:riverbankcomputing.com/static/Docs/PyQt5/…
    • 我之前点击了向上箭头,很长一段时间我认为这是标记好的答案,今天我在向下箭头下方看到了一个检查标签。
    猜你喜欢
    • 2019-01-05
    • 2011-07-15
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    相关资源
    最近更新 更多