c++ - QT - 如何在滚动区域上添加按钮(具有绝对位置)
问题描述
我有以下布局
我在这里尝试做的是在滚动区域上放置一个自定义小部件(蓝色小部件)。
这是我的大纲的外观:
我想在轮廓之间添加那个 BLUE 小部件home_page
,scrollArea
或者就 GUI 而言,我想在 GUI 上添加那个按钮,ScrollAreaContent
但是我不想在我的那一刻把那个按钮从它的位置移开正在搬家ScrollAreaContent
。
auto sizeX = 0.25 * w;
auto sizeY = 0.9 * h;
ui->scrollArea->setBaseSize(w,h);
ui->scrollAreaWidgetContents->setBaseSize(w,h);
ui->home_page->layout()->setMargin(0);
ui->home_page->layout()->setContentsMargins(0,0,0,0);
ui->scrollAreaWidgetContents->setLayout(new QHBoxLayout());
ui->scrollAreaWidgetContents->layout()->setMargin(0);
ui->scrollAreaWidgetContents->layout()->setContentsMargins(0,0,0,0);
//This list is going to contain the buttons from scrollAreaWidgetContents
auto buttons = new QList<MenuHomeButton *>();
//...
//ADD buttons
//...
ui->stackedWidget->setCurrentIndex(0);
for (auto button : *buttons) {
ui->scrollAreaWidgetContents->layout()->addWidget(button);
connect(button, SIGNAL(buttonClicked(int)), ui->stackedWidget, SLOT(setCurrentIndex(int)));
}
QScroller::grabGesture(ui->scrollArea, QScroller::LeftMouseButtonGesture);
你们中有人知道我该怎么做吗?
解决方案
如果您想自己定位小部件,则不得将其添加到布局中。
您可以将小部件创建为容器的子小部件,然后在其上调用 show 方法。这样,新小部件将位于相对于容器的位置 (0,0)(当然,您可以将其移动到任何您想要的位置)。您仍然可以在容器中使用布局来管理其他小部件,即:滚动区域。
我认为在您的情况下,您可以执行以下操作:
auto but=new QPushButton(ui->scrollAreaWidget);
but->show();
另外,我强烈建议您在计划这样做时不要使用设计器,根据我的经验,它更清楚。