为了账号安全,请及时绑定邮箱和手机立即绑定

如何为 QTreeWidgetItem 添加彩色动画?

如何为 QTreeWidgetItem 添加彩色动画?

POPMUISE 2022-06-28 18:06:52
我需要向 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'  
查看完整描述

1 回答

?
跃然一笑

TA贡献1826条经验 获得超6个赞

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


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_())


查看完整回答
反对 回复 2022-06-28
  • 1 回答
  • 0 关注
  • 275 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号