我正在尝试使用QPainter
类绘制一些形状并将其保存到磁盘。据我所知,最简单的方法是使用QPainter
绘制到QPixmap
,通过QLabel
在像素图中进行可视化,并使用QPixmap::save
。
但是当我运行这个测试时,我在QWidget中只看到一个小黑盒子。
MyWidget::MyWidget()
{
std::cout << "MyWidget > ." << std::endl;
l = new QLabel();
l->setParent(this);
pixmap = new QPixmap(460, 480);
painter = new QPainter(pixmap);
}
MyWidget::~MyWidget()
{
delete pixmap;
delete painter;
}
void MyWidget::paintEvent(QPaintEvent *event)
{
std::cout << "dudee" << std::endl;
painter->begin(pixmap);
painter->drawLine(1,1,100,100);
QPen myPen(Qt::black, 2, Qt::SolidLine);
painter->setPen(myPen);
painter->drawLine(100,100,100,1);
painter->setRenderHint(QPainter::Antialiasing, true);
painter->setPen(QPen(Qt::black, 3, Qt::DashDotLine, Qt::RoundCap));
painter->setBrush(QBrush(Qt::green, Qt::SolidPattern));
painter->drawEllipse(200, 80, 400, 240);
painter->end();
l->setPixmap(*pixmap);
}
我试图添加一些l-&gt; update()但它不会改变任何东西..
它应该是一个动画。我通过QTimer获得动画工作,每隔n毫秒调用绘制函数(而不是作为答案建议的paintEvent)
答案 0 :(得分:5)
解决方案:
已编辑的代码: 编辑问题的简单类:
AnimationSample.h
#ifndef ANIMATIONSAMPLE_H
#define ANIMATIONSAMPLE_H
#include <QWidget>
#include <QPixmap>
#include <QLabel>
#include <QPointer>
#include <QTimer>
class AnimationSample
: public QWidget
{
Q_OBJECT
public:
AnimationSample( QWidget *parent = NULL );
~AnimationSample();
private slots:
void onTick();
private:
QPointer< QLabel > m_label;
QPointer< QTimer > m_timer;
int m_salt;
};
#endif // ANIMATIONSAMPLE_H
AnimationSample.cpp
#include "AnimationSample.h"
#include <QPixmap>
#include <QPainter>
AnimationSample::AnimationSample( QWidget *parent )
: QWidget( parent )
, m_salt( 1 )
{
m_label = new QLabel( this );
m_label->setFixedSize( 100, 100 );
m_timer = new QTimer( this );
connect( m_timer, SIGNAL( timeout() ), SLOT( onTick() ) );
m_timer->start( 250 );
}
AnimationSample::~AnimationSample()
{
}
void AnimationSample::onTick()
{
QPixmap pic( 100, 100 );
QPainter p( &pic );
QPen myPen( Qt::black, 2, Qt::SolidLine );
p.setPen( myPen );
p.drawLine( 0, 0, m_salt, m_salt );
m_salt = (m_salt + 1) % 100;
m_label->setPixmap( pic );
}