简体   繁体   中英

Add a scrolabble window with buttons into my scene

I am trying to add a box(position:1140, 485 and size:225, 365) with a scroll-able layout with buttons inside the layout. I do NOT want the box to move/resize. I want the box to have a scroll bar with which we can scroll through all the buttons in it.

The code I have so far is not working at all, all I get is a Layout full of buttons with a stretching box(which i DO NOT want). The only thing that is working so far is that the buttons are added to the box in the right-ish way.

All I need is to make the box scroll-able and make it so that the box does NOT resize itself when there are too many buttons.

Here is my code:

QWidget *box = new QWidget(); //creating the box and placing it where I want it
box->move(1145, 485);
box->resize(225, 365);

gameScene->addWidget(box); //adding it to the main scene

//where AM i supposed to use this?
QScrollArea *scrollArea = new QScrollArea();

QGridLayout *layout = new QGridLayout();
box->setLayout(layout);

//testButtons
QPushButton *testButton1 = new QPushButton("Button1");
layout->addWidget(testButton1);
   ....
QPushButton *testButtonN = new QPushButton("ButtonN");
layout->addWidget(testButtonN);

我的项目图片

You can see the box on the BOTTOM RIGHT with the title GAME TRANSCRIPT. I just want the box to contain buttons just like it is. But i Do NOT want it resizing and i DO want it scroll-able since it is cutting off buttons at the bottom.

QScrollArea setWidget takes in a QWidget as a parameter. This means you'll have to add buttons to a layout as children and the layout is added as a child to the widget, then you'll be able to set the widget as a child of QScrollArea. See example below:

QWidget *window = new QWidget;
QPushButton *button1 = new QPushButton("button1");
QPushButton *button2 = new QPushButton("button2");
QPushButton *button3 = new QPushButton("button3");
QPushButton *button4 = new QPushButton("button4");
QPushButton *button5 = new QPushButton("button5");

QGridLayout * mainLayout = new QGridLayout;
QWidget* buttonsContainer = new QWidget;
QVBoxLayout *buttonsContainerLayout = new QVBoxLayout;
QScrollArea *scrollArea = new QScrollArea();

buttonsContainerLayout->addWidget(button1);
buttonsContainerLayout->addWidget(button2);
buttonsContainerLayout->addWidget(button3);
buttonsContainerLayout->addWidget(button4);
buttonsContainerLayout->addWidget(button5);

buttonsContainer->setLayout(buttonsContainerLayout);

scrollArea->setWidget(buttonsContainer);

mainLayout->addWidget(scrollArea);

window->setLayout(mainLayout);
window->setWindowTitle(
    QApplication::translate("testscrollable", "Test Scrollable"));
window->show();

Note https://doc.qt.io/qt-5/qscrollarea.html#setWidget

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM