Adjusting QPen thickness when scaling QGraphicsView?
Asked Answered
W

1

11

One amazing feature of QGraphicsView is its ability to scale itself with its scene's content (every QGraphicsItem inserted in the scene actually). The QPixmap that I have inserted scales correctly, meaning that if I provide a scale factor of 4x4 with this:

view->scale(4,4);

Pixmap are zoomed as I want to do.

But this is not the case of the rects that I am used to drawing; they aims to surrounds the pixmaps that I draw on my scene and regardless of the scale factor, they keep a thickness of 1 instead of - I guess - 4.

I have been searching documentation about all of that stuff, trying to figure out the exact purpose of "cosmetics pen", but I still can't manage to make my rectangle go thicker.

Last notice: I have a custom QGraphicsItem and the QPen which is used to draw the rectangled is instanciated on-the-fly in the

virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);

method.

Does it matter?

Thanks in advance and apologies for my lack of experience / knowledge in both the Qt framework and the drawing algorithms fields...

Wilmoth answered 29/10, 2012 at 11:11 Comment(2)
Show use the code where you create the QPen.Adulteress
Here we go: QPen borderPen(Qt::black); borderPen.setCosmetic(false); painter->setPen(borderPen);Wilmoth
D
17

It doesn't really matter where you instantiate the QPen.

QPen has a default width of 0. This is a special value that means cosmetic is true and the width is actually 1. So if you don't want the pen to be cosmetic you have to set it to the desired width. You might also need to set cosmetic to false.

Here is a simple example:

#include <QtGui>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QGraphicsView view;
    QGraphicsScene scene;

    QGraphicsRectItem *item1 = scene.addRect(20, 20, 20, 20);
    QGraphicsRectItem *item2 = scene.addRect(50, 20, 20, 20);

    QPen pen1, pen2;
    pen1.setWidth(5);
    pen2.setWidth(5);
    pen1.setCosmetic(true);
    pen2.setCosmetic(false);

    item1->setPen(pen1);
    item2->setPen(pen2);

    view.setScene(&scene);
    view.scale(4, 4); // both rects are the same size, but one a has wider pen
    view.show();

    return a.exec();
}
Debacle answered 29/10, 2012 at 12:8 Comment(2)
The example works fine, but when I comment the setWidth() lines, both rectangles keep the same thickness in there edges. Thank you anywayWilmoth
That's because the default width is 0, which is cosmetic. You must change the width to 1 or greater if you want the thickness to increase with the scale.Debacle

© 2022 - 2024 — McMap. All rights reserved.