现在的位置: 首页 > 综合 > 正文

Laying out widgets 布局的使用 (三)

2013年10月12日 ⁄ 综合 ⁄ 共 2254字 ⁄ 字号 评论关闭

  所有的widgets 都可以放到一个布局上进行自动布局
  布局类有三个:
  QHBoxLayout---- lays out widgets horizontally from left to right(right to left for some cultures)

  QVBoxLayout---- lays out widgets vertically from top to bottom

  QGridLayout---- lays out widgets in a grid

  添加部件时 比如定义了几个部件,直接调用addWidget() 成员函数就可以

  比如:
  

   QSlider *slider=new QSlider // 滑动杆
   QSpinBox *spin= new QSpinBox  
   QHBoxLayout *layout=new QHBoxLayout;

   layout->addWidget(slider)
   layout->addWidget(spin)

   这样就把QSlider 和 QSpinBox 控件添加到了布局 layout这种

   下面接着要做的就是把布局添加到窗口中
   使用Widget::setLayout()

   如:
  
   QWidget *window=new QWidget;
  
   window->setLayout(layout)

  1.  1 #include <QApplication>
  2.  2 #include <QHBoxLayout>
  3.  3 #include <QSlider>
  4.  4 #include <QSpinBox>
  5.  5 int main(int argc, char *argv[])
  6.  6 {
  7.  7     QApplication app(argc, argv);
  8.  8     QWidget *window = new QWidget;
  9.  9     window->setWindowTitle("Enter Your Age");
  10. 10     QSpinBox *spinBox = new QSpinBox;
  11. 11     QSlider *slider = new QSlider(Qt::Horizontal);
  12. 12     spinBox->setRange(0, 130);
  13. 13     slider->setRange(0, 130);
  14. 14     QObject::connect(spinBox, SIGNAL(valueChanged(int)),
  15. 15                      slider, SLOT(setValue(int)));
  16. 16     QObject::connect(slider, SIGNAL(valueChanged(int)),
  17. 17                      spinBox, SLOT(setValue(int)));
  18. 18     spinBox->setValue(35);
  19. 19     QHBoxLayout *layout = new QHBoxLayout;
  20. 20     layout->addWidget(spinBox);
  21. 21     layout->addWidget(slider);
  22. 22     window->setLayout(layout);
  23. 23     window->show();
  24. 24     return app.exec();
  25. 25 }

自己写的

  1. #include <QtGui/QApplication>
  2. #include "qt.h"
  3. #include <qpushbutton>
  4. #include<QHBoxLayout>
  5. #include <QSlider>
  6. #include<QSpinBox>
  7.  int main(int argc, char *argv[])
  8.  {
  9.      QApplication app(argc, argv);
  10.     QWidget *window = new QWidget;
  11.     window->setWindowTitle("Enter Your Age");
  12.      QSpinBox *spinBox = new QSpinBox;
  13.     QSlider *slider = new QSlider(Qt::Horizontal);
  14.    spinBox->setRange(0, 130);
  15.      slider->setRange(0, 130);
  16.     QObject::connect(spinBox, SIGNAL(valueChanged(int)),
  17.                       slider, SLOT(setValue(int)));
  18.      QObject::connect(slider, SIGNAL(valueChanged(int)),
  19.                      spinBox, SLOT(setValue(int)));
  20.     spinBox->setValue(35);
  21.      QHBoxLayout *layout = new QHBoxLayout;
  22.      layout->addWidget(spinBox);
  23.      layout->addWidget(slider);
  24.     window->setLayout(layout);
  25.     window->show();
  26.      return app.exec();
  27.  }

  
 

抱歉!评论已关闭.