#include <QApplication>
#include <QLabel>
#include <QCheckBox>
#include <QPainter>
#include <QMouseEvent>
#include <QLayout>
Q_OBJECT
public:
DrawLine() : size(17), scale(40), radius(5), active(-1), hover(-1),
image
(size, size,
QImage::Format_RGB32), round
(false),
antialiasing(false) {
int sz = size*scale;
setMinimumSize(sz, sz);
int half = sz/2;
pts
[0] = QPoint(half
/2, half
);
pts
[1] = QPoint(half
*3/2, half
);
renderLine();
setMouseTracking(true);
}
void emitCoords() {
if (round) {
str.sprintf("P0: (%d, %d) P1: (%d, %d)", p0.x(), p0.y(), p1.x(), p1.y());
} else {
str.sprintf("P0: (%.2f, %.2f) P1: (%.2f, %.2f)", p0.x(), p0.y(), p1.x(), p1.y());
}
emit coordsUpdated(str);
}
public slots:
void setRound(bool round) {
this->round = round;
renderLine();
}
void setAntialiasing(bool antialiasing) {
this->antialiasing = antialiasing;
renderLine();
}
signals:
void coordsUpdated
(QString coords
);
protected:
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
QRgb cur = image.pixel(i, j);
p.
fillRect(i
*scale, j
*scale, scale, scale,
QColor(cur
));
}
}
p.setPen(Qt::lightGray);
int sz = size*scale;
for (int i = 0; i < size; ++i) {
int x = i*scale;
p.drawLine(x, 0, x, sz);
p.drawLine(0, x, sz, x);
}
p.
setRenderHint(QPainter::Antialiasing);
p.setPen(Qt::blue);
p.drawLine(pts[0], pts[1]);
p.setPen(Qt::NoPen);
for (int i = 0; i < 2; ++i) {
p.setBrush(i == hover ? Qt::yellow : Qt::blue);
p.drawEllipse(pts[i], radius, radius);
}
}
if (active == -1 && event->button() == Qt::LeftButton) {
int current = index(event->pos());
if (current != -1)
active = current;
}
}
if (active != -1 && event->button() == Qt::LeftButton) {
active = -1;
}
}
if (active != -1) {
pts[active] = event->pos();
renderLine();
}
int current = index(event->pos());
if (current != hover) {
hover = current;
update();
}
}
private:
}
return (coords
(idx
) - QPointF(0.5,
0.5)).
toPoint();
}
for (int i = 0; i < 2; ++i) {
if (QLineF(p, pts
[i
]).
length() <
= radius
) return i;
}
return -1;
}
void renderLine() {
image.fill(qRgb(255, 255, 255));
p.
setRenderHint(QPainter::Antialiasing, antialiasing
);
p.setPen(Qt::red);
if (round) {
p.drawLine(roundCoords(0), roundCoords(1));
} else {
p.drawLine(coords(0), coords(1));
}
emitCoords();
update();
}
int size;
int scale;
int radius;
int active;
int hover;
bool round;
bool antialiasing;
};
int main(int argc, char *argv[])
{
DrawLine draw;
QObject::connect(&round,
SIGNAL(toggled
(bool)),
&draw,
SLOT(setRound
(bool)));
QObject::connect(&antialiasing,
SIGNAL(toggled
(bool)),
&draw,
SLOT(setAntialiasing
(bool)));
layout.addWidget(&round, 0, 0);
layout.addWidget(&antialiasing, 0, 1);
layout.addWidget(&label, 0, 2);
layout.addWidget(&draw, 1, 0, 1, 3);
layout.setColumnStretch(2, 1);
widget.setLayout(&layout);
widget.show();
draw.emitCoords();
return app.exec();
}
#include "main.moc"