2011-06-14 51 views
1

我有一種形式,我正在申請ScrollArea,但它沒有得到正確應用? 我想將四個按鈕放置在可滾動區域中,並且當按鈕增加時,滾動條應該出現在那裏垂直向下sc下。QT中的ScrollArea問題?

當前當我試圖添加更多按鈕時,按鈕與組合框重疊並且不會向下生長。

這裏是我的代碼:

QPushButton *b1 = new QPushButton(strsearch); 
      QPushButton *b2 = new QPushButton(strsearch); 
      QPushButton *b3 = new QPushButton(strsearch); 
      QPushButton *b4 = new QPushButton(strsearch); 

b1->setStyleSheet(

       "background-image: url(:/user.gif);" 
       "background-repeat:no-repeat;" 
       "background-attachment:fixed;" 
       "background-position:left top;" 
       "border-style: outset;" 
       "background-color : black;" 
       "border-width: 2px;" 
       "border-radius: 10px;" 
       "border-color: black;" 
       "font: bold 16px;" 
       "color: black;" 
       "min-width: 10em;" 
       "min-height: 0.75em;" 
       "margin: 0 1px 0 1px;" 
       "color:rgb(255,255,255);" 
       "padding: 6px;" 
       ); 



b2->setIcon(QIcon(":/user.gif")); 
      b2->setIconSize(QSize(160, 26)); 
      b3->setIcon(QIcon(":/user.gif")); 
      b3->setIconSize(QSize(160, 26)); 
      b4->setIcon(QIcon(":/user.gif")); 
      b4->setIconSize(QSize(160, 26)); 

QGridLayout *layout = new QGridLayout; 
layout->addWidget(b1, 1, 0); 
      layout->addWidget(b2, 2, 0); 
      layout->addWidget(b3, 3, 0); 
      layout->addWidget(b4, 4, 0); 
layout->addWidget(scrollArea); 
    layout->setAlignment(Qt::AlignBottom); 
    setLayout(layout); 

回答

5
//Create the buttons 
QPushButton *b1 = new QPushButton("Button 1"); 
QPushButton *b2 = new QPushButton("Button 2"); 
QPushButton *b3 = new QPushButton("Button 3"); 
QPushButton *b4 = new QPushButton("Button 4"); 

//Add the buttons to a vertical layout (faster than grid layout) 
QVBoxLayout *scrollLayout = new QVBoxLayout; 
scrollLayout->addWidget(b1); 
scrollLayout->addWidget(b2); 
scrollLayout->addWidget(b3); 
scrollLayout->addWidget(b4); 

//Create a viewport widget that contains the layout with buttons 
QWidget *viewport = new QWidget; 
viewport->setLayout(scrollLayout); 

//Add the viewport to the scroll area 
QScrollArea *scrollArea = new QScrollArea; 
scrollArea->setWidget(viewport); 

//Add the scroll area to your main window's layout 
mainLayout->addWidget(scrollArea); 
+0

@Riccardo:但我想滾動僅適用於按鈕區域,他們會根據您code.What放在QVBoxLayout是應用mainLayout-需要> addWidget(scrollArea);.我可以使它像這樣scrollLayout-> addWidget(scrollArea); – user662285 2011-06-14 10:24:35

+0

明白了。謝謝。 – user662285 2011-06-14 10:30:03

+0

@Riccardo:如何檢查控制是否添加到主佈局不再添加它? – user662285 2011-06-14 12:20:00