0

这是我的代码:

#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。我知道如果我创建一个继承了QWidget,但我想尝试一下如何让它在一个文件中工作)??非常感谢~;-)

4

2 回答 2

4

我认为,错误在这里:

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

错误说,您只是在绘画之前没有激活 Painter,例如在打开文件之前尝试读取文件。你初始化了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*。祝你好运

于 2013-03-25T13:43:28.110 回答
0

您只能使用QPainterinQWidgetpaintEvent功能。因此,编写一个继承QWidget并实现其paintEvent功能的新类。

于 2013-03-25T15:05:56.977 回答