方法一:無參構造畫家時,需要手動調用begin(this)和end() 函數
void MyWidget::paintEvent(QPaintEvent *)
{
QPainter p;
p.begin(this);
p.drawLine(...); // drawing code
p.end();
}
。。
方法二:有參構造畫家時,系統會自動調用begin(this)和end() 函數,可以立即直接使用畫家進行繪圖。
這個構造函數對於壽命較短的畫家很方便,例如在QWidget::paintEvent()中,並且只應該使用一次
void MyWidget::paintEvent(QPaintEvent *)
{
QPainter p(this);
p.drawLine(...); // drawing code
}
方法三:創建畫布,將其作為參數構造畫家
QPixmap pix=QPixmap(size());//創建畫布
pix.fill(Qt::white);
QPainter painter(&pix);//創建畫家
.......
//使用畫家繪圖
p.drawLine(...); // drawing code
.......
//將pixmap繪制到窗體上
painter.end();
painter.begin(this);
painter.drawPixmap(0,0,pix);//將pixmap畫到窗體