当我点击绘图按钮时,我想绘制一个网格(一系列线条),当我点击清除按钮时,我希望它们清除。
我让网格显示为一个独立的程序,但我无法弄清楚如何将它与QPushButton结合起来。
在程序运行时单击“绘图”按钮时,我收到以下消息。
“QPainter :: begin:Paint device返回引擎== 0,键入:1 QPainter :: setPen:画家不活跃“
谢谢
#include <QtGui>
#include <QPainter>
#include "myqtapp.h"
// including <QtGui> saves us to include every class user, <QString>, <QFileDialog>,...
myQtApp::myQtApp(QWidget *parent)
{
setupUi(this); // this sets up GUI
// signals/slots mechanism in action
connect( pushButton_draw, SIGNAL( clicked() ), this, SLOT( draw() ) );
connect( pushButton_clear, SIGNAL( clicked() ), this, SLOT( clear() ) );
connect( pushButton_about, SIGNAL( clicked() ), this, SLOT( about() ) );
}
void myQtApp::draw()
{
//draw the grid
int lineSpacing(30),// line spacing in pixels
numberOfLines;
QPen pen(Qt::black, 2, Qt::SolidLine);
QPainter painter(this);
painter.setPen(pen);
//Grid takes up at most a 400x400 area starting at (right 150, down 50) from upper left
numberOfLines = 400/lineSpacing; //Round down grid size to fit in 400x400
for(int i = 0; i<numberOfLines; i++){
painter.drawLine(150, 50+i*lineSpacing, 150+(numberOfLines-1)*lineSpacing, 50+i*lineSpacing);
painter.drawLine(150+i*lineSpacing, 50, 150+i*lineSpacing, 50+(numberOfLines-1)*lineSpacing );
}
}
答案 0 :(得分:4)
您遇到的问题是因为您试图在窗口小部件的paintEvent()调用之外使用QPainter绘制UI - 来自Qt文档:
QPainter的常见用法是在widget的paint事件中:Construct 并定制(例如设置笔或画笔)画家。然后画画。 记得在绘图后销毁QPainter对象。
如果您尝试在paintEvent()调用之外绘制窗口小部件,则结果是不可预测的。
这样做的正确方法是这样的:
// myQtApp.h
class myQtApp : public QWidget
{
Q_OBJECT
public:
myQtApp(QWidget *parent = 0); // Constructor as you have
protected:
void paintEvent(QPaintEvent *event); // This is re-implemented from QWidget
protected slots:
void draw();
private:
bool drawTheLines;
}
和
// myQtApp.cpp
void myQtApp::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
if(drawTheLines)
{
// Do the drawing here - as in your current draw() function
}
QWidget::paintEvent(event); // call the base class so everything else is drawn OK
}
void draw();
{
drawTheLines = true;
update(); // This forces a repaint of the widget with paintEvent()
}