一:解释
QPainter 只能在paintEvent 调用的原因.
最近创建了一个继承 QWidget 的窗口部件,使用 QPainter 绘制需要的内容,一部分在 paintEvent 中使用 QPainter,另一部分在自定义函数中使用 QPainter,发现运行时警告:
QWidget::paintEngine: Should no longer be called kernel……
QPainter::begin: Paint device returned engine == 0, type: 1 painting……
查找 QPainter 文档,发现如下事项:
Warning: When the paintdevice is a widget, QPainter can only be used inside a paintEvent() function or in a function called by paintEvent().
Warning: When the paintdevice is a widget, QPainter can only be used inside a paintEvent() function or in a function called by paintEvent().
这才明白,QPainter 默认只能在 paintEvent 里面调用,
在别处绘制就会遇到警告。另外,
在构造函数中设置
属性:
this->setAttribute(Qt::WA_PaintOutsidePaintEvent);
是可以 在paintEvent()之外绘制; 但不幸的是,该属性只支持X11,对于 Windows、Mac OS X、Embedded Linux 均不予支持。
this->setAttribute(Qt::WA_PaintOutsidePaintEvent);
是可以 在paintEvent()之外绘制; 但不幸的是,该属性只支持X11,对于 Windows、Mac OS X、Embedded Linux 均不予支持。
设计思想:
其次,在 paintEvent 中使用QPainter和开发要求不冲突。你在slot中update或repaint不就行了.设计相关变量进行存储相关的数据,然后再paintEvent出进行绘制的时候再进行相关调用.
二:实现在MainWindow进行贴图效果.
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPainter>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::paintEvent(QPaintEvent *pain)
{
QPainter MyPaint(this);
MyPaint.drawText(QRect(0,0,100,40),QString("hello world"));
MyPaint.drawPixmap(rect(), QPixmap(":/Images/logo"));
}