как добавить цветную анимацию в QTreeWidgetItem? - PullRequest
1 голос
/ 18 октября 2019

Мне нужно добавить цветную анимацию в 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 Ответ

1 голос
/ 18 октября 2019

Свойство (pyqtProperty в PyQt) действует только в объектах QObject, но в этом случае 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_())
...