QT学习之路---信号槽

#include<QApplication>
#include<QPushButton>

int main(int argc,char *argv[])
{
    QApplication a(argc,argv);
    QPushButton *button = new QPushButton("Quit");
    QObject::connect(button,SIGNAL(clicked()),&a,SLOT(quit()));
    button->show();
    return a.exec();
}

 其中:

 QObject::connect(button,SIGNAL(clicked()),&a,SLOT(quit()));

Qobject是所有类的根,Qt使用这个Qobject实现了一个单根继承的c++。它里面有一个connect静态函数,用于连接信号槽

具体来说:QApplication的实例a说,如果button发出了clicked信号,你就去执行我的quit函数。所以,当我们点击button的时候,a的quit函数被调用,程序退出。

 

  注意:Qt中头文件和类名是一致的。也就是说,如果你要使用某个类的话,它的类名就是它的头文件名。

#include<QLabel>

QLabel *label = new QLabel("Hello,world");

创建一个QLabel对象,并且能够显示Hello,world!字符串。和其他库的Label控件一样,这里用来显示文本的。

  在一个Qt源代码中,以下两条语句是必不可少的:

QApplication app(argc,argv);

return app.exec();

 

 

#include<QApplication>
#include<QWidget>
#include<QSpinBox>
#include<QSlider>
#include<QHBoxLayout>

int main(int argc,char *argv[])
{
    QApplication app(argc,argv);
    QWidget *window = new QWidget;
    window->setWindowTitle("Enter your age");

    QSpinBox *spinBox = new QSpinBox;
    QSlider *slider = new QSlider(Qt::Horizontal);
    spinBox->setRange(0,130);
    slider->setRange(0,130);

    QObject::connect(slider,SIGNAL(valueChanged(int)),spinBox,SLOT(setValue(int)));
    QObject::connect(spinBox,SIGNAL(valueChanged(int)),slider,SLOT(setValue(int)));
    spinBox->setValue(35);

    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(spinBox);
    layout->addWidget(slider);
    window->setLayout(layout);

    window->show();
    return app.exec();
}

   这里使用了两个新的组件:QSpinBox和QSlider,以及一个新的顶级窗口QWidget。

QSpinBox是一个有上下箭头的微调器,QSlider是一个滑动杆。

posted on 2016-09-28 11:34  白宫飘红旗  阅读(206)  评论(0编辑  收藏  举报