本来以为
QPainter只能在PainterEvent函数内绘图,今天看了 自带Queued Custom Type Example的例子,发现它是在一个槽函数中操作QPainter绘制一个
QPixmap的。
然后我自己也试验一下,具体
界面如图

主
窗口派生于QWidget,然后包含一个子QWidget,和两个
按钮,分别用了两个
布局。按下Magnigy按钮想在子Widget中绘制一个矩形,每次按下,矩形放大两倍,按下Lessen,子Widget中的矩形缩小两倍。主要调用了如下的函数。
void Widget::myPaint(QWidget *w)
{
QPainter painter;
painter.begin(w);
painter.fillRect(0,0,width,height,QColor(Qt::red);
painter.end();
}
但是一调用就提示QPainter::begin: Paint device returned engine == 0, type: 1
查了下手册只有下面三种情况会
出错painter->begin(0); // impossible - paint device cannot be 0QPixmap image(0, 0);painter->begin(&image); // impossible - image.isNull() == true;painter->begin(myWidget);painter2->begin(myWidget); // impossible - only one painter at a time我的这个子Widget已经new了,应该不是空的。
感觉在PainterEvent外绘图也蛮好的,特别是要对某个控件绘图,不用再派生一个该控件,再重写PainterEvent函数那么麻烦了。不知道错在哪里?