Qt中QScrollArea類的簡單使用心得


       平台: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 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM