最近学习Qt 自定义绘画时碰到两个问题,问题如下:
自定义绘画图形,采用重写QPaintEvent,发现绘画不起作用;
1、Qpainter不刷新,解决方法:在触发刷新是,调用updata()函数强行更新。
问题
其中Qpainter 的父类应该是具体绘画的widget;
对于QGraphiscView:我所碰到的问题如下:

输出:
QPainter::fillPath: Painter not active
QPainter::setPen: Painter not active
QPainter::restore: Unbalanced save/restore
QWidget::paintEngine: Should no longer be called
QPainter::begin: Paint device returned engine == 0, type: 1
QPainter::setRenderHint: Painter must be active to set rendering hints
QPainter::save: Painter not active
QPainter::translate: Painter not active
QPainter::setPen: Painter not active
void ViewPager::paintEvent(QPaintEvent *e)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.save();
m_indicatorYpos = m_scene->height() - m_indicatorPadding\
-m_ViewButtonMagin - m_ViewItemH - 10;
painter.translate(width() / 2,m_indicatorYpos);
QPen pen;
pen.setColor(m_colorBorder);
pen.setWidth(3);
painter.setPen(pen);
int startToCenter = (m_indicatorCircleMargin / 2 + m_indicatorCircleR) * (m_pagesCount - 1);
for (int i = 0; i < m_pagesCount; i++)
{
int center = -startToCenter + i * (m_indicatorCircleMargin + 2 * m_indicatorCircleR);
painter.drawEllipse(QPoint(center, 0), m_indicatorCircleR, m_indicatorCircleR);
}
float currentPoint = startToCenter * (m_count - 1)*1.0f;
qDebug() << "repaint" << m_count;
QPainterPath path;
path.addEllipse(QPointF(currentPoint, 0), m_indicatorCircleR, m_indicatorCircleR);
painter.fillPath(path, m_colorFill);
/*绘制指示圆孔两边的线段*/
pen.setWidth(4);
pen.setColor(m_colorBorder);
pen.setStyle(Qt::SolidLine);
pen.setCapStyle(Qt::RoundCap);
pen.setJoinStyle(Qt::BevelJoin);
painter.setPen(pen);
QLine leftLine(-200, 0, -50, 0);
QLine rightLine(50,0, 200, 0);
painter.drawLine(leftLine);
painter.drawLine(rightLine);
painter.restore();
// QWGraphicsView::paintEvent(e);
}
经过思考:
发现问题出现在:
QPainter painter(this);,经过查询帮助手册:
如下
大概意思是,QGraphicsView 绘画图形是在Viewport上绘画, 通过使用viewport() 可获取绘画窗口,因此,QPainter painter(this),不应该在QGraphicsView上申请画家,而是在viewport上申请画家。
解决
只需要修改 **QPainter painter(this->viewport());**即可解决问题,
问题:

单击按键图形无变化。按键槽函数如下:
void ViewPager::onRightClicked()
{
m_direct = Right;
m_count++;
if(m_count > 2)
{
m_count = 0;
}
this->update();
}
void ViewPager::onLeftClicked()
{
m_direct = Left;
m_count--;
if(m_count < 0)
{
m_count = 2;
}
this->update();
}
经过测试:每次点击按键,paintEvent都执行了,为什么没有刷新显示到窗口上。
解决
后面经过思考,修改代码如下:
将 this->update()修改为this->viewport()->update();问题解决。效果如下:

单击右键:

总结:
对于使用自定义绘画时, 申请的画家parent应该为实际的绘画窗口,并不一定全是this,需要强制更新绘画,采用实际绘画窗口update()函数即可。

在Qt自定义绘画时遇到QPainter不刷新的问题,原因是QPainter对象的父类应为具体绘画的widget,而非QGraphicsView本身。解决方法是在QGraphicsView的viewport上创建QPainter对象,如`QPainter painter(this->viewport())`。另外,单击按键无响应是因为更新操作应针对viewport,即使用`viewport()->update()`而不是`this->update()`。
1928

被折叠的 条评论
为什么被折叠?



