I need a little help in resizing a 2D figure. After 4 hours of searching and trying different methods, I figure I should post a question here.
[Project]: I am trying to draw and resize and rotate a figure using sliders. For some reason it doesn't want to act upon the figure. I want to increase the size by 1 for every time the slider value changes and back.
I don't want to use QPainter::scale or rotate.
[Code]:
#include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
a = 250;
b = 150;
c = 200;
d = 150;
ui->setupUi(this);
connect(ui->horizontalSlider,SIGNAL(valueChanged(int)),this,SLOT(change(int)));
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::paintEvent(QPaintEvent *e)
{
QPainter painter(this);
painter.fillRect(a,b,c,d, Qt::green);
}
void Dialog::change(int value1)
{
if(value1 > value2)
{
next = ++value1;
a = a;
b = b;
c = c + next;
d = d + next;
}
}
[Header]:
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QtGui>
#include <QtCore>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
public slots:
void change(int value1);
private:
Ui::Dialog *ui;
int value2, next;
protected:
void paintEvent(QPaintEvent *e);
int a,b,c,d;
};
Calling QWidget::update() will update the form and trigger a paint event.
Assuming you have a horizontalSlider
working in the range [-100; 100], here is a small example:
dialog.h:
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
protected:
void paintEvent(QPaintEvent *e);
private:
Ui::Dialog *ui;
int a,b,c,d;
};
#endif // DIALOG_H
dialog.cpp:
#include "dialog.h"
#include "ui_dialog.h"
#include <QPainter>
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
ui->horizontalSlider->setMinimum(-100);
ui->horizontalSlider->setMaximum(100);
a = 10;
b = 10;
c = 200;
d = 150;
connect(ui->horizontalSlider,SIGNAL(valueChanged(int)),this,SLOT(update()));
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::paintEvent(QPaintEvent *e)
{
QPainter painter(this);
painter.fillRect(a,
b,
c + ui->horizontalSlider->value(),
d + ui->horizontalSlider->value(),
Qt::green);
}
If you want to scale the rectangle with its center as pivot point just use:
void Dialog::paintEvent(QPaintEvent *e)
{
QPainter painter(this);
painter.fillRect(a - ui->horizontalSlider->value(),
b - ui->horizontalSlider->value(),
c + ui->horizontalSlider->value() * 2,
d + ui->horizontalSlider->value() * 2, Qt::green);
}
In this example the rectangle is resizing around the top-left pivot point. In case this is not what you want let me know and I'll be more explicit in my answer.