2015-03-02 54 views
3

所以我有這個QFrame它是父窗口小部件(在代碼中表示爲this)。在這個小部件中,我想在頂部10px處放置一個QWidget(底部爲10px,因此它的高度爲140px,而父層爲160px)。 QWidget將在垂直佈局中的滾動區域內具有多個自定義按鈕,以便當組合的按鈕高度超過高度(140px)時,自動滾動設置。由於滾動不是針對整個父窗口小部件的,而僅適用於子窗口小部件,因此滾動應該僅應用於此處的子窗口小部件。這裏是我的代碼:QScrollArea與QWidget和QVBoxLayout沒有像預期的那樣工作

//this is a custom button class with predefined height and some formatting styles 
class MyButton: public QPushButton 
{ 

public: 
    MyButton(std::string aText, QWidget *aParent); 

}; 

MyButton::MyButton(std::string aText, QWidget *aParent): QPushButton(QString::fromStdString(aText), aParent) 
{ 
    this->setFixedHeight(30); 
    this->setCursor(Qt::PointingHandCursor); 
    this->setCheckable(false); 
    this->setStyleSheet("background: rgb(74,89,98); color: black; border-radius: 0px; text-align: left; padding-left: 5px; border-bottom: 1px solid black;"); 
} 

//this is where I position the parent widget first, and then add sub widget 
this->setGeometry(x,y,width,160); 
this->setStyleSheet("border-radius: 5px; background:red;"); 

//this is the widget which is supposed to be scrollable 
QWidget *dd = new QWidget(this); 
dd->setGeometry(0,10,width,140); 
dd->setStyleSheet("background: blue;"); 

QVBoxLayout *layout = new QVBoxLayout(); 
dd->setLayout(layout); 

for (int i = 0; i < fValues.size(); i++) 
{ 
    MyButton *button = new MyButton(fValues[i],dd); 
    layout->addWidget(button); 
} 

QScrollArea *scroll = new QScrollArea(this); 
scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); 
scroll->setWidget(dd); 

出乎我的意料,這是我得到什麼(附圖片)。我做錯了什麼,以及如何解決這個問題?

enter image description here

+0

這是有道理的,觀察調試信息。 – AlexanderVX 2015-03-03 05:57:54

回答

5

你搞砸了項目的堆棧。具有滾動區域的構思是這樣的:

  • 在底部是父窗口部件(例如QDialog
  • 在此之上是在此之上固定大小
  • 的滾動區域(QScrollArea)在一些大小,這裏通常只是其中的一部分是可見的小窗口(QWidget)(它應該比scrollarea更大)
  • 在此之上是一個佈局
  • 最後:佈局管理子項(情侶QPushButton這裏)

試試這個代碼:

int 
main(int _argc, char** _argv) 
{ 
    QApplication app(_argc, _argv); 

    QDialog * dlg = new QDialog(); 
    dlg->setGeometry(100, 100, 260, 260); 

    QScrollArea *scrollArea = new QScrollArea(dlg); 
    scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); 
    scrollArea->setWidgetResizable(true); 
    scrollArea->setGeometry(10, 10, 200, 200); 

    QWidget *widget = new QWidget(); 
    scrollArea->setWidget(widget); 

    QVBoxLayout *layout = new QVBoxLayout(); 
    widget->setLayout(layout); 

    for (int i = 0; i < 10; i++) 
    { 
     QPushButton *button = new QPushButton(QString("%1").arg(i)); 
     layout->addWidget(button); 
    } 

    dlg->show(); 

    return app.exec(); 
} 

值得一提的約QScrollArea::setWidgetResizable,其中根據其內容動態調整子控件的大小。

而結果是這樣的:

enter image description here

相關問題