Custom coordinate system using QGraphicsView, QGraphicsScene and QGraphicsRectItem
-
Dear Qt community,
In the past days I've been struggling to implement a simple graphical tool which will draw rectangles next to each other in real time, allowing only a maximum of n rectangles in the window. I have been able to do this before with a QOpenGLWidget using a QPainter and drawing rectangles. The reason I'm switching to the QGraphicsScene is that it is able to draw QGraphicsRectItems. These have nice properties like setting a tooltip.
The main problem is that I cannot seem to understand the coordinate system when using the QGraphicsView and the QGraphicsScene. The current simple problem I'm not able to solve is to draw a rectangle in the topleft quarter of the window. Ideally, this rectangle would resize along the window as the window dimensions change. I'm using scene->setSceneRect() to (from my understanding) change the coordinates to whatever needed and then plot the QGraphicsRectItem with corresponding coordinates, like is possible with QPainter (setWindow() method and add rectangles with corresponding coordinates).
The simple reproducible code is as follows:
#include <QHBoxLayout> #include <QGraphicsView> #include <QApplication> #include <QGraphicsRectItem> #include <QWidget> int main(int argc, char* argv[]) { QApplication app(argc, argv); QWidget window; QGraphicsView *view = new QGraphicsView(); QGraphicsScene *scene = new QGraphicsScene(); view->setScene(scene); view->setAlignment(Qt::AlignLeft | Qt::AlignTop); scene->setSceneRect(0, 0, 100, 100); QGraphicsRectItem *item = scene->addRect(QRectF(0, 0, 50, 50)); item->setBrush(Qt::red); // // Fill full screen // scene->setSceneRect(0, 0, 10000, 10000); // QGraphicsRectItem *item = scene->addRect(QRectF(0, 0, 5000, 5000)); // item->setBrush(Qt::red); QHBoxLayout *layout = new QHBoxLayout; layout->addWidget(view); window.setLayout(layout); window.show(); return app.exec(); }
An example of the result is as follows:
As you can see, the rectangle does not fill the topleft quarter of the window. Further, the code that is commented out fully fills the window and adds scrollbars.
I've tried various things like mapToScene(), mapFromScene(), mapToParent() etc., but I have a strong feeling that I don't fully understand these methods yet, but they did not help me with this problem either.
Do you know how the code can be changed such that the rectangle is placed nicely on the topleft quarter of the screen (and ideally resizes along with changes in the parent window dimension)?
Thanks in advance.
-
Does anyone maybe have an idea?
-
QGraphicsView::fitInView using your rectangle coordinates as input?
-
Since your view is in a layout... have you tried to set the layout margin to 0?