gpt4 book ai didi

c++ - 如何动画QBrush的颜色

转载 作者:太空狗 更新时间:2023-10-29 20:24:59 25 4
gpt4 key购买 nike

我想为 QBrush 的颜色设置动画。有关更多详细信息,请参见下面的代码

那是我的 .h 文件

class Cell : public QObject, public QGraphicsRectItem
{
Q_OBJECT
Q_PROPERTY(QBrush brush READ brush WRITE set_Brush)
public:
QBrush _brush() const;
void set_Brush(const QBrush&);
Cell(QGraphicsItem *parent = 0); //конструктор
}

那是我的 .cpp 文件

Cell::Cell(QGraphicsItem *parent)
: QObject(), QGraphicsRectItem(parent)
{
this->setRect(0, 0, Scale, Scale);
}

QBrush Cell::_brush() const
{
return this->brush();
}

void Cell::set_Brush(const QBrush & brush)
{
this->setBrush(brush);
}

这就是动画:

QPropertyAnimation* animation = new QPropertyAnimation(selectedCell, "brush");
animation->setDuration(10000);
animation->setStartValue(QBrush(QColor(255,0,0)));
animation->setEndValue(QBrush(QColor(0,255,0)));
animation->start();

但是它不起作用,没有任何反应,画笔的颜色和以前一样。我应该怎么做才能修复它?

最佳答案

QT 不知道如何在开始 QBrush 和结束 QBrush 之间执行转换。 QBrush 具有比颜色更多的属性,您可以设想一个颜色保持不变而只有图案发生变化的动画。因此,没有默认支持这种转换。正如@fscibe 所暗示的,您可以编写自己的方法来执行转换,在该转换中您指定要如何从一个 QBrush 转换到另一个。

粗略的例子:

QVariant myColorInterpolator(const QBrush &start, const QBrush &end, qreal progress)
{
QColor cstart = start.color();
QColor cend = end.color();
int sh = cstart.hsvHue();
int eh = cend.hsvHue();
int ss = cstart.hsvSaturation();
int es = cend.hsvSaturation();
int sv = cstart.value();
int ev = cend.value();
int hr = qAbs( sh - eh );
int sr = qAbs( ss - es );
int vr = qAbs( sv - ev );
int dirh = sh > eh ? -1 : 1;
int dirs = ss > es ? -1 : 1;
int dirv = sv > ev ? -1 : 1;

return QBrush(QColor::fromHsv( sh + dirh * progress * hr,
ss + dirs * progress * sr,
sv + dirv * progress * vr), progress > 0.5 ? Qt::SolidPattern : Qt::Dense6Pattern );


}

这会执行颜色过渡,但也会在过渡过程中更改图案。

那么这里将是您代码中此转换的虚拟应用程序:

int main(int argc, char** argv)
{
QApplication app(argc,argv);
QGraphicsView *view = new QGraphicsView;
QGraphicsScene *scene = new QGraphicsScene;
QDialog *dialog = new QDialog;
QGridLayout *layout = new QGridLayout;
layout->addWidget(view);
view->setScene(scene);
scene->setSceneRect(-500,-500,1000,1000);
dialog->setLayout(layout);
dialog->show();

Cell *selectedCell = new Cell;
scene->addItem(selectedCell);

qRegisterAnimationInterpolator<QBrush>(myColorInterpolator);
QPropertyAnimation* animation = new QPropertyAnimation(selectedCell, "brush");
animation->setDuration(10000);
animation->setStartValue(QBrush(Qt::blue));
animation->setEndValue(QBrush(Qt::red));
animation->start();

return app.exec();
}

显然这是一个虚拟示例,对于颜色更改,它正在重新发明轮子,正如您从 fscibe 答案中看到的那样,但这只是为了向您展示定义您自己的过渡方法,例如QBrush您可以做的不仅仅是改变颜色。

关于c++ - 如何动画QBrush的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25514812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com