组装丰富的积木
这个例子显示了如何把两个窗口部件封装成一个新的组件和使用许多窗口部件是多么的容易。首先,我们使用一个自定义的窗口部件作为一个子窗口部件。
//main.cpp
#include <QApplication>
#include <QFont>
#include <QGridLayout>
#include <QLCDNumber>
#include <QPushButton>
#include <QSlider>
#include <QVBoxLayout>
#include <QWidget>
//LCDRange类
class LCDRange : public QWidget
{
public:
LCDRange(QWidget *parent = 0);
};
LCDRange::LCDRange(QWidget *parent)
: QWidget(parent)
{
//LCD数字
QLCDNumber *lcd = new QLCDNumber(2);
lcd->setSegmentStyle(QLCDNumber::Flat);
//Slider
QSlider *slider = new QSlider(Qt::Horizontal);
slider->setRange(0, 99);
slider->setValue(0);
connect(slider, SIGNAL(valueChanged(int)),lcd, SLOT(display(int)));
//布局
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(lcd);
layout->addWidget(slider);
setLayout(layout);
}
//MyWidget类
class MyWidget : public QWidget
{
public:
MyWidget(QWidget *parent = 0);
};
MyWidget::MyWidget(QWidget *parent)
: QWidget(parent)
{
//创建quit按钮
QPushButton *quit = new QPushButton(tr("Quit"));
quit->setFont(QFont("Times", 18, QFont::Bold));
connect(quit, SIGNAL(clicked()), qApp, SLOT(quit()));
QGridLayout *grid = new QGridLayout; //网格布局
//3x3
for (int row = 0; row < 3; ++row) {
for (int column = 0; column < 3; ++column) {
LCDRange *lcdRange = new LCDRange; //创建LCD+Slider
grid->addWidget(lcdRange, row, column);
}
}
QVBoxLayout *layout = new QVBoxLayout; //垂直布局
layout->addWidget(quit);
layout->addLayout(grid); //子布局
setLayout(layout); //设置布局
}
int main( int argc, char *argv[])
{
QApplication app(argc, argv);
//创建MyWidget的一个实例
MyWidget widget;
widget.show();
return app.exec();
}