Solved Get the MainWindow size
-
I have a
MainWindow
with agraphicsView
widget.I would like to match the sizes of the Main Window and the
graphicsView
widget.
I'm trying this:MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); setCentralWidget(ui->graphicsView); // Try to get the MainWindow size and set these values to the image size: int sizeX = this->size().width(); int sizeY = this->size().height(); // Create and init the image: QImage image = QImage(sizeX, sizeY, QImage::Format_RGB32); // Fill the image with colors: for (int x = 0; x < sizeX; x++) { for (int y = 0; y < sizeY; y++) { image.setPixel(x, y, qRgb(x * 256 / sizeX, y * 256 / sizeY, 200)); } } // Create a graphics scene: QGraphicsScene* graphic = new QGraphicsScene(this); graphic->setSceneRect(0, 0, sizeX, sizeY); // Set the image: graphic->addPixmap(QPixmap::fromImage(image)); // Try to fit in view: ui->graphicsView->fitInView(0, 0, sizeX, sizeY); // Display it on the UI: ui->graphicsView->setScene(graphic); }
But the result is this window with scroll bars!!
How can I init the MainWindow and the
graphicsView
widget with the same size? -
Hi,
As suggested in the fitInView documentation, it's usual to call it in a resizeEvent re-implementation.
-
For now, I'm resolving this problem with this temporary source-code:
// Get the correct MainWindow size to use with graphicsView widget: int width = this->size().width() - 20; // Magic number, but works int height = this->size().height() - 40; // Magic number, but works
-
Try to get the size when the widget is shown, not when you create it - then there are no valid size information available iirc.
-
Hi,
As suggested in the fitInView documentation, it's usual to call it in a resizeEvent re-implementation.
-
@Christian-Ehrlicher thank you...
I understand your point, but now I have a logistic doubt.I have only one
QMainWindow
and, inside of it, I have these two things: AQImage
and aGraphicsView
.
So, I need to set:
-> TheQImage
size
-> ThegraphicsView
sizeWhen the application starts, the
QMainWindow
appears and these values must be valids to create a good UI.How could I set these values before the
QMainWindow
initialization? -
@SGaist Yes, I'm using it in both cases:
1- On theQMainWindow
constructor
2- On theresizeEvent()
It solves the problem!
Thank you again! -
You're welcome !
Since you have it working now please mark the thread as solved using the "Topic Tools" button so that other forum users may know a solution has been found :-)
Note that you can also mark an answer as the "thread correct answer" by using the three vertical dots on the right of each answer.