我有以下代码在 QtCore 5.0 中绘制一条动画线,因此它看起来像是由笔逐像素绘制的。
我的想法是使用计时器并将 timeout() 与调用 QGraphicsLineItem::setLine() 的插槽连接起来,所以这里是我如何画线并创建 SLOT move() 以循环并逐渐画线:myLine.h
#ifndef MYLINE_H
#define MYLINE_H
#include <QGraphicsLineItem>
class myLine : public QObject, public QGraphicsLineItem
{
Q_OBJECT
public:
myLine();
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
private slots:
void mySlot();
private:
QLineF thisline;
};
#endif // MYLINE_H
我的线路.cpp
myLine::myLine()
{
thisline.setLine(0,0,50,50);
}
void myLine::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
painter->setRenderHint(QPainter::Antialiasing);
painter->setPen(QPen(Qt::red, 8, Qt::SolidLine, Qt::RoundCap, Qt::MiterJoin));
painter->setBrush(QBrush(Qt::blue, Qt::DiagCrossPattern));
painter->drawLine(thisline);
}
void myLine::mySlot()
{
for (int i = 1; i < 100; i++)
{
QLineF line = this->line();
line.setLine(0,0,50+i,50+i);
update();
}
}
然后调用一个GraphicsScene
scene = new QGraphicsScene(this);
ui->graphicsView->setScene(scene);
ui->graphicsView->setSceneRect(0,0,700,700);
ui->graphicsView->setRenderHint(QPainter::Antialiasing);
myLine *line = new myLine();
scene->addItem(line);
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), line, SLOT(mySlot()));
timer->start(100);
但是,在编译时它只会立即绘制一条线。我想这就是问题在循环中,但我无法确切地弄清楚。所以如果有人能给我一个提示,我真的很感激。