C++ GUI Programming with Qt3(系列三 试翻)

类别:编程语言 点击:0 评论:0 推荐:

C++ GUI Programming with Qt3(系列三 试翻)

        Qt widgets emit signals to indicate that a user action or a change of state has occurred. For instance , QpushButton emits a clicked() single when the user click the button。A singal can be connected to a function (called a slot in that context),so that when the singal is emitted the slots is automactically executed. In out example, we connect the button's clicked() singal to the Qapplication object's quit() slot. The SINGNAL() and SLOT() macros are part of syntax. They are explained in more detail in the next chapter.
        We will now build the application, we assume that you have created a directory called quit containing quit.cpp . Run qmake in the quit directory to generate the project file.then run it again to generate a makefile.
 Qmake -project
Qmke quit.pro
        Now build the application ,and run it,if you click Quit, or press Space(which presses the button),the application will terminate. 

        The next example demonstrates how to use signals and slots to synchronize two widgets. The application ask for the user's age, which the user can enter by manipulating either a spin box or slider.
 
 
        The application consists of tree widgets:a Qslider,a QspinBox,and a QHBox(horizontal layout box). The QHBox is application's main widget. The SpinBox and the Qslider,are rendered inside the QHBox.

001 #include <qapplication.h>
002 #include <qhbox.h>
003 #include <qslider.h>
004 #include <qspinbox.h>
005 int main(int argc, char *argv[])
006 {
007     QApplication app(argc, argv);
008     QHBox *hbox = new QHBox(0);
009     hbox->setCaption("Enter Your Age");
010     hbox->setMargin(6);
011     hbox->setSpacing(6);

012     QSpinBox *spinBox = new QSpinBox(hbox);
013     QSlider *slider = new QSlider(Qt::Horizontal, hbox);
014     spinBox->setRange(0, 130);
015     slider->setRange(0, 130);
016     QObject::connect(spinBox, SIGNAL(valueChanged(int)),
017     slider, SLOT(setValue(int)));
018     QObject::connect(slider, SIGNAL(valueChanged(int)),
019     spinBox, SLOT(setValue(int)));
020     spinBox->setValue(35);
021     app.setMainWidget(hbox);
022     hbox->show();
023     return app.exec();
024 }         Qt窗体控件用向外发送信号来表示用户的动作发生或本身状态的改变。例如,当用户单击程序中的Button该QpushButton对象就会发送一个clicked()信号。信号可以和某个特定的函数关联(向下文中成为反应槽)。关联的结果就是当一个信号被发送时和他关联的函数将会被调用。在本例中,我们把按钮的clicked()消息和Qapplication 对象的quit()反应函数关联起来。SINGNAL()和SLOT()宏是语法的一部分,在下一章将对他们进行进一步的描述。
        现在我们来编译连接该程序。我们认为你已经新建了一个名为quit的文件夹,并且该文件夹中有一个quit.cpp文件。在quit目录中运行qmake程序来产生该项目的项目文件。再次运行qmake程序来产生makefile。
Qmake -project
Qmake quit.pro
        建立(译:用make命令)并运行该程序。当你单击或按下空格键是这个程序就会退出了(译:或叫终止运行)。
下来的例子将演示如何使用信号和反应槽来同步两个不同的窗体控件。该程序要求用户输入年龄。用户可以通过操作cpin box或slider两种方式来完成输入。

本文地址:http://com.8s8s.com/it/it25515.htm