PDA

View Full Version : Draw a shape upon clicking a button



ZsCosa
21st July 2013, 20:19
Hi, I'm new to Qt so please bare with me for a second here, and thank you for reading onward.

I'm trying to create a simple application in Qt Creator 5.1.0, which displays a 'Draw' button and upon clicking it will draw something. For the button: I just drag & drop a simple pushButton in Qt Designer.

Here is my header mydrawbutton.h


#ifndef MYDRAWBUTTON_H
#define MYDRAWBUTTON_H

#include <QMainWindow>
#include <QPainter>

#include "ui_mydrawbutton.h"


class mydrawbutton : public QMainWindow, public Ui::mydrawbutton
{
Q_OBJECT

public:
explicit mydrawbutton(QWidget *parent = 0);
~mydrawbutton();
protected:
void drawShape(QPaintEvent *);

private slots:
void draw();

private:
Ui::mydrawbutton *ui;
bool m_draw;
};

#endif // MYDRAWBUTTON_H


and source mydrawbutton.cpp:



#include <QPushButton>

#include "mydrawbutton.h"


mydrawbutton::mydrawbutton(QWidget *parent) :
QMainWindow(parent)
{
setupUi(this);
m_draw = false;
connect(drawButton, SIGNAL(clicked()), this, SLOT(draw()));
}

mydrawbutton::~mydrawbutton()
{
delete ui;
}



void mydrawbutton::drawShape(QPaintEvent *)
{
QPainter painter(this);
if (!m_draw){
painter.setPen( Qt::green );
painter.setBrush( Qt::green );
painter.drawRect(10, 10, 100, 100);
}
}

void mydrawbutton::draw()
{
m_draw = !m_draw;
update();
}


The problem is: when compile it does display the 'Draw' button, however nothing happened when clicking it. I've spent quite sometime reading around and trying to fix it, but haven't been able to make it work. Hope someone can help me fix it. Oh and if I'm missing any bits of information that you need, please tell me. Thank you!

anda_skoa
22nd July 2013, 11:22
I am not sure what you are expecting.

Your slot changes the value of m_draw and then tells your main window subclass to update. Since m_draw is not used anywhere in drawing code, the window will be drawn exactly as it was before.

It looks like you want to the drawShape() method to be executed but you don't call it from anywhere.

A naive approach would be to call it from paintEvent(), but you really don't want to do that for a QMainWindow subclass.

So create a simple QWidget subclass that does the slot and drawing an put an instance if it as the main window's central widget.

Cheers,
_

ZsCosa
22nd July 2013, 17:30
Ah, I see the problem here. Thanks very much for your answer, I'll try to work it out.

Cheers!