平台:windows 64位
Qt版本:5.5.1 MinGW 32bit
根據自己目前的需求簡單說下怎麼在QScrollArea滾動窗口中實現多個控件的滾動顯示,先看看最終效果:

先說一下在QScrollArea滾動窗口中要添加控件要使用QScrollArea::setWidget(QWidget * widget)這個函數,當添加的控件顯示范圍大於scrollArea則會出現滾動條,但是從名字可以看出這個函數是用於設置一個QWidget,而不能用於不斷的添加QWidget,所以這裡面並不能像大家想的那樣來直接實現上面的效果,而是需要創建一個自己的QWidget,再在其中來添加自己需要的控件。
下面給出代碼看看,由於我的滾動窗口是已經用設計器添加到對話框上的,所以我直接用ui->scrollArea來調用,buttonListWidget是我重新實現的QWidget子類,等會在下面可以看到實現代碼:
1 buttonListWidget *buttonList = new buttonListWidget(this); 2 buttonList->initWidget(strList); 3 ui->scrollArea->setWidget(buttonList);
buttonListWidget類,其實內容不多,但是主要是掌握到方法:
buttonListWidget.h
1 class buttonListWidget : public QWidget
2 {
3 Q_OBJECT
4 public:
5 explicit buttonListWidget(QWidget *parent = 0);
6 void initWidget(QStringList& nameList);
7
8 signals:
9
10 public slots:
11 };
buttonListWidget.cpp
1 buttonListWidget::buttonListWidget(QWidget *parent) : QWidget(parent)
2 {
3
4 }
5
6 void buttonListWidget::initWidget(QStringList &nameList)
7 {
8 QHBoxLayout *layout = new QHBoxLayout(this);
9 foreach (QString str, nameList)
10 {
11 QPushButton *button = new QPushButton(str, this);
12 button->setMinimumSize(button->size());
13 layout->addWidget(button);
14 }
15 this->setLayout(layout);
16 }