QScrollArea:由垂直滚动条引起的水平滚动条

QScrollArea: horizontal scrollbar caused by vertical scrollbar

本文关键字:滚动条 水平 QScrollArea 垂直      更新时间:2023-10-16

我有一个简单的对话框,里面有一个QScrollArea:

// Vertical container for the dialog
QVBoxLayout *cont = new QVBoxLayout;
this->setLayout(cont); //"this" is my derived QDialog class
// ScrollArea for iconFrame
QScrollArea *scroll = new QScrollArea;
cont->insertWidget(0, scroll );
// The frame to be added to the QScrollArea
QFrame *iconFrame = new QFrame;
scroll->setWidget(iconFrame);
scroll->setWidgetResizable(true);
// Grid layout for iconFrame
QGridLayout *grid = new QGridLayout;
iconFrame->setLayout(grid);
// Second child widget for the dialog
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel);
cont->insertWidget(1, buttonBox);
int maxcol = int(ceil(sqrt(numberOfButtons)));
if(maxcol > 6) maxcol = 6;
for(int i=0; i<numberOfButtons; i++)
{
QPushButton *button= new QPushButton("My Button");
button->setFixedSize(48, 48);
int row = int(floor(i/maxcol));
grid->addWidget(button, row, i-row*maxcol);
}

由于最多有6列,因此框架和对话框将垂直增长。

它按预期工作,只是绘制水平滚动条只是因为垂直滚动条增加了宽度。

我尝试过sizePolicies和sizeConstraints的不同组合,但似乎没有任何效果。

如何去掉水平滚动条?

您可以使用滚动条策略来抑制滚动条:

scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

请注意,内容可能会被剪辑。

对于滚动区域有更多可用空间的情况,您可以尝试widgetResizable:

scroll->setWidgetResizable(true);

与其说是一个解决方案,不如说是一种变通方法,但它确实有效。

iconFrame->adjustSize(); // Only necessary when contents of iconFrame have changed
if(iconFrame->height() > scroll->height())
scroll->setMinimumWidth(iconFrame->width()+scroll->verticalScrollBar()->height());