代码之家  ›  专栏  ›  技术社区  ›  bur

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

  •  -2
  • bur  · 技术社区  · 6 年前

    我有一个简单的对话框,里面有一个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和sizeconstraint的不同组合,但似乎没有任何效果。

    2 回复  |  直到 6 年前
        1
  •  1
  •   king_nak    6 年前

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

    scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    

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

    widgetResizable

    scroll->setWidgetResizable(true);
    
        2
  •  0
  •   bur    6 年前

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

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