Using code instead of the editor.
-
This is probably very basic but i'm new to Qt and i can't seem to find info on how to do some things in code instead of the editor.
I want to add a QScrollArea to the main window, and set the windows layout to QHBoxLayout. I can do it in the editor but when i try do it in code the scroll area just appears as a small box in the top left corner over the the top of the menu bar and doesn't scale with the window or anything.
Here's the code i tried.
in MainWindow.hQHBoxLayout* m_layout; QScrollArea* m_scrollArea;
in MainWindow.cpp
m_layout = new QHBoxLayout(this); m_scrollArea = new QScrollArea(this); this->layout()->addWidget(m_scrollArea);
Again sorry if this is basic stuff I just can't find what i'm suppose to do.
-
what is the this object ? Is it QMainWindow or QWidget ? My guess is that it must be QMainWindow. When you run the program, it must be giving warning saying that "Not able to set the layout". Please check that.
-
Hi @Sunnykins,
Since you are creating your own layout usingQHBoxLayout
you should add the widget to the layout you created.layout()
returns the already set layout to mainwindow. Instead set your newly created layout usingsetLayout
. Something like this:m_layout = new QHBoxLayout; m_scrollArea = new QScrollArea(this); m_layout->addWidget(m_scrollArea); ui->centralWidget->setLayout(m_layout); //set layout to MainWindow's central widget
-
ui->centralWidget->setLayout(m_layout);
Thanks p3c0, that fixed it. I did try:
this->setLayout(m_layout);
but nothing seemed to happen.
Yeah dheerendra i was getting that warning. I'm guess the window itself and the ui are different things? do i always go through the ui pointer when i add a widget etc?Also since the layout doesn't have a parent does that mean i have to explicitly delete it since it won't be deleted when it's parent is?
edit: actually does the layout need to be a pointer at all? guess i could just make it an object.
-
Hi and welcome to devnet,
the solution is
m_layout->addWidget(m_scrollArea); this->setLayout(m_layout);
-
@Sunnykins said:
ui->centralWidget->setLayout(m_layout);
Thanks p3c0, that fixed it. I did try:
this->setLayout(m_layout);
but nothing seemed to happen.
Yeah dheerendra i was getting that warning. I'm guess the window itself and the ui are different things? do i always go through the ui pointer when i add a widget etc?Also since the layout doesn't have a parent does that mean i have to explicitly delete it since it won't be deleted when it's parent is?
setLayout here would set layout for the mainwindow which fails because it already has a layout set for central widget.