Important: Please read the Qt Code of Conduct -

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:


    #include "widget.h"
    #include <QApplication>
    int main(int argc, char *argv[])
        QApplication a(argc, argv);
        Widget w;;
        return a.exec();


    #ifndef WIDGET_H
    #define WIDGET_H
    #include <QWidget>
    namespace Ui {
    class Widget;
    class Widget : public QWidget
        explicit Widget(QWidget *parent = 0);
        Ui::Widget *ui;
        QImage rectImg_;
        void paintEvent(QPaintEvent *);
        void resizeEvent(QResizeEvent *);
    #endif // WIDGET_H


    #include <QPainter>
    #include "widget.h"
    #include "ui_widget.h"
    Widget::Widget(QWidget *parent) :
        ui(new Ui::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);
        QImage empty(size(), QImage::Format_ARGB32_Premultiplied);
        rectImg_ = empty;
        rectImg_.fill(qRgba(255, 255, 255, 255));
        QPainter painter;
        //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));

  • Moderators

    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.

Log in to reply