很多人使用了QWindow之后不知道要怎么去绘制成自己想要的样子。这里提供了一个简单的例子来帮组实现QWindow的自绘:
首先定义一个测试的QWindow对象PaintWindow:
#ifndef PAINTWINDOW_H
#define PAINTWINDOW_H
#include <QBackingStore>
#include <QWindow>
class PaintWindow: public QWindow
{
public:
PaintWindow(QWindow* parent = NULL);
~PaintWindow();
private:
QBackingStore mBackingStore;
protected:
bool event(QEvent *e);
void draw();
};
#endif // PAINTWINDOW_H
其中我定义了一个draw函数,在这个函数中进行绘制(这个函数的操作类似于QWidget的PaintEvent)
接下来看实现:
#include "PaintWindow.h"
#include <QPainter>
PaintWindow::PaintWindow(QWindow *parent)
:QWindow(parent)
,mBackingStore(this)
{
this->setOpacity(0.5);
}
PaintWindow::~PaintWindow()
{
}
bool PaintWindow::event(QEvent *e)
{
if(e->type()==QEvent::Expose || e->type()==QEvent::Resize)
{
draw();
}
return QWindow::event(e);
}
void PaintWindow::draw()
{
QRect tagRect(QPoint(0,0), this->size());
mBackingStore.resize(tagRect.size());
mBackingStore.beginPaint(tagRect);
QPainter p(mBackingStore.paintDevice());
p.fillRect(tagRect, QColor(255,0,0));
mBackingStore.endPaint();
mBackingStore.flush(tagRect);
}
主要是每次draw的时候都要初始化一下BackingStore,在绘制完成的时候需要endPaint和flush
创建这个类的实例运行起来就得到一个红色半透明的QWindow。需要绘制更复杂的样子则在draw函数中操作!