基本Qt GUI:QPushButton用于绘制直线
我希望在单击“绘制”按钮时绘制栅格(一系列线),并希望在单击“清除”按钮时将其清除 我让网格显示为一个独立的程序,但我不知道如何将它与QPushButton结合起来 当程序运行时单击Draw按钮时,我收到以下消息 “QPaint::begin:绘制设备返回的引擎==0,类型:1 QPaint::setPen:画师未激活” 多谢各位基本Qt GUI:QPushButton用于绘制直线,qt,Qt,我希望在单击“绘制”按钮时绘制栅格(一系列线),并希望在单击“清除”按钮时将其清除 我让网格显示为一个独立的程序,但我不知道如何将它与QPushButton结合起来 当程序运行时单击Draw按钮时,我收到以下消息 “QPaint::begin:绘制设备返回的引擎==0,类型:1 QPaint::setPen:画师未激活” 多谢各位 #include <QtGui> #include <QPainter> #include "myqtapp.h" // includin
#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 );
}
}
#包括
#包括
#包括“myqtapp.h”
//包含使我们能够包含每个类用户,。。。
myQtApp::myQtApp(QWidget*父项)
{
setupUi(this);//此设置GUI
//作用中的信号/插槽机制
连接(按钮_-draw,信号(点击()),此,插槽(draw());
连接(按钮清除,信号(点击()),此,插槽(清除());
连接(按钮_关于,信号(点击()),此,插槽(关于());
}
void myQtApp::draw()
{
//画网格
int行间距(30),//以像素为单位的行间距
行数;
QPen笔(Qt::黑色,2,Qt::实线);
油漆工(本);
画师:画笔;
//网格从左上角(右150,下50)开始最多占用一个400x400区域
numberOfLines=400/行间距;//向下取整网格大小以适应400x400
对于(int i=0;i您遇到的问题是,您试图在小部件的paintEvent()调用之外使用QPainter在UI上绘图-来自Qt文档:
QPainter的常见用法是在小部件的绘制事件:Construct中
并自定义(例如,设置笔或画笔)画家。然后绘制。
请记住在绘制后销毁QPaint对象
如果尝试在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()
}