如何在一个cpp文件中使用QPainter?

时间:2013-03-25 13:07:10

标签: qt makefile qwidget qpainter

这是我的代码:

#include<QApplication>
#include<QWidget>
#include<QPaintEvent>
#include<QPainter>

int main(int argc,char**argv)
{
QApplication app(argc,argv);
QWidget*wid=new QWidget;
wid->setWindowTitle("sb");

QPainter paint;
paint.setWindow(0,0,900,900);
QRectF border(3*45-20,25,670,850);
QRectF inter(3*45,45,630,810);
paint.setPen(Qt::NoPen);
paint.setBrush(QBrush(Qt::darkMagenta,Qt::SolidPattern));
paint.drawRect(border);
paint.setBrush(QBrush(Qt::gray,Qt::SolidPattern));
paint.drawRect(inter);//
paint.setPen(QPen(Qt::darkGray,3,Qt::SolidLine,Qt::RoundCap,Qt::RoundJoin));
paint.setPen(Qt::NoPen);

paint.beginNativePainting();
wid->show();
return app.exec();
}

在qmake -project,qmake,make之后,它出现了如下错误:

kl@kl-Latitude-D630:~/QTproj/t1$ ./t1 
QPainter::setWindow: Painter not active
QPainter::setPen: Painter not active
QPainter::setBrush: Painter not active
QPainter::drawRects: Painter not active
QPainter::setBrush: Painter not active
QPainter::drawRects: Painter not active
QPainter::setPen: Painter not active
QPainter::setPen: Painter not active
QPainter::beginNativePainting: Painter not active

嗯~~如何仅在一个cpp文件中激活QPainter(我不想使用诸如paint.h,paint.cpp和main.cpp之类的单独文件。我知道如果我创建一个文件,我可以使它工作class继承了QWidget,但我想尝试一下如何让它在一个文件中工作)?非常感谢〜; - )

2 个答案:

答案 0 :(得分:4)

我想,错误就在这里:

QPainter paint;
paint.setWindow(0,0,900,900);

错误说,你只是在绘画之前没有激活Painter,比如在打开之前尝试读取文件。 你初步画了画家,但没有告诉他画在哪里。查看一些文档 - http://harmattan-dev.nokia.com/docs/library/html/qt4/qpainter.html#QPainter

只需在QPainter::begin ( QPaintDevice * device )后添加QPainter paint;或将该行更改为QPainter::QPainter ( QPaintDevice * device )

例如 - QPainter p(img);其中img是QImage *。祝你好运

答案 1 :(得分:0)

您只能在QPainter的{​​{1}}功能中使用QWidget。 所以写一个继承自paintEvent的新类并实现它的QWidget函数。