Unsolved Align QPainterPath figure to one side of QImage while resizing
-
Basically, i have a rectangle that should be resizable according to widget current size and stick to right side of a widget. It worked fine, until i forced rectangle to keep his proportions. To clarify, here's the picture of what i need to do: IMAGE
obviously, QPainter::translate doesn't work well for me.
here's the code:
main.cpp
#include "widget.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); Widget w; w.show(); return a.exec(); }
widget.h
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = 0); ~Widget(); private: Ui::Widget *ui; QImage rectImg_; protected: void paintEvent(QPaintEvent *); void resizeEvent(QResizeEvent *); }; #endif // WIDGET_H
widget.cpp
#include <QPainter> #include "widget.h" #include "ui_widget.h" Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); } Widget::~Widget() { delete ui; } void Widget::paintEvent(QPaintEvent *) { QPainter painter(this); painter.drawImage(QPointF(0.0, 0.0), rectImg_); } void Widget::resizeEvent(QResizeEvent *) { //draw rectangle QPainterPath rectangle; rectangle.moveTo(20.0, 30.0); rectangle.lineTo(80.0, 30.0); rectangle.lineTo(80.0, 70.0); rectangle.lineTo(20.0, 70.0); rectangle.closeSubpath(); QImage empty(size(), QImage::Format_ARGB32_Premultiplied); rectImg_ = empty; rectImg_.fill(qRgba(255, 255, 255, 255)); QPainter painter; painter.begin(&rectImg_); painter.setRenderHint(QPainter::Antialiasing); //keep proportions of rectangle const int side = qMin(width(), height()); painter.scale(side / 100, side / 100.0); //painter.translate(20.0,0.0) //doesnt' do what i expect painter.setPen(QPen(Qt::red, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); painter.drawPath(rectangle); painter.end(); }
-
@dream_captain
i suggest you avoid using transformations (scale, translate, ...) on the painter.
Why don't you just calculate a QRect and paint it?
Do you depend on QPainterPath?
Why do you paint into an image in the resize event handler, instead of doing the painting directly in the paintEvent handler? -
@raven-worx
Thank you for reply.
My widget has two layers, that should be responsive to mouse events and position. I use painter path because the original figure that i use in my application is far more complex than a rectangle and has two layers. My application runs on a very slow device and it should work well on different resolutions, so i must minimize the amount of costly operations (like QPainter::drawPath();). The idea is to create and scale a QImage of one layer and QImage of another layer in resizeEvent() and then simply draw them in paintEvent() depending on current mouse position. It's far less costly.