Qt入门事故:
在执行第一个Hello Qt程序的时候,意外发生了,编辑器报错:
Cannot run compiler 'g++'
根据熟悉经验,判断出一定是编译器出了问题,有可能是未将MinGW所在目录放入环境变量中,所以我将项目中用到的编译器的地址加入了环境变量中,但是依旧出现相同的问题,于是继续百度,看博客,但是始终没有解决。所以我最终选择重新安装Qt开发环境,在进行安装步骤的时候,意识到了在当初安装Qt未选择编译器的选项,导致了无法编译的情况,问题解决!
步入正题!
经过书中第一个Demo得出:
图形界面中,需要构造一个主窗口,窗口还可以包括其他的窗口部件,这就对应到了C++中的父类和子类的问题,一个Qt程序的执行需要定义一个QApplication,然后创建窗口控件的程序,通常来说一些控件是隐藏的,所以要调用一个show方法显示空间,如:
QLabel *label = new QLabel ("Hello Qt!"); //new 一个QLabel控件
label->show();
Amazing! 一段方法写完之后就需要写行代码去响应实际的用户操作,则需要在结尾return这个最初创建的QApplication,如:
return app.exec();
学到下面,更神奇的是!!!
Qt竟然还可以支持HTML的样式,以下代码:
QLabel *label = new QLabel ("<h2><i>Hello</i>"
"<font color=red>Qt!</font></h2>");
效果如下:
下一步就是开始了解建立连接
这是最重要的部分!Qt相对于C++最大的不同就是信号(SIGNAL)和槽(SLOT)代码如下:
QObject::connect(button,SIGNAL(clicked()),
&app,SLOT(quit()));
代码实现过程就是,如果点击button,信号clicked 就可以触发并传给app执行槽中quit的方法,太神奇了!
相对重要的,也是学习Qt的初衷:窗口部件布局!
对控件进行布局需要用到布局管理器layout manager :它就是一个能够对其所负责窗口部件的尺寸大小和位置进行设置的对象,它也有三个主要的布局管理器类:
·QHBoxLayout:在水平方向上排列窗口部件,从左往右。
·QVBoxLayout:在竖直方向上排列窗口部件,从上到下。
·QGridLayout: 把各个窗口部件排列在一个网格中。代码如:
QVBoxLayout *layout = new QVBoxLayout;//QHBoxLayout水平,QGridLayout网格
layout->addWidget(spinBox);
layout->addWidget(slider);
完整实例:
滑块和显示文字
#include<QApplication>
#include<QHBoxLayout>
#include<QSlider>
#include<QSpinBox>
int main_layout(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(spinBox,SIGNAL(valueChanged(int)),
slider,SLOT(setValue(int)));
QObject::connect(slider,SIGNAL(valueChanged(int)),
spinBox,SLOT(setValue(int)));
spinBox->setValue(0);
QVBoxLayout *layout = new QVBoxLayout;//QHBoxLayout水平,QGridLayout网格
layout->addWidget(spinBox);
layout->addWidget(slider);
window->setLayout(layout);
window->show();
return app.exec();
}
结果如下:
Hello Qt
#include "mainwindow.h"
#include <QApplication>
//#include<QPushButton>
#include<QLabel>
int main_helloQt(int argc, char *argv[])
{
QApplication a(argc, argv);
//QPushButton *button = new QPushButton("quit");
//QLabel *label = new QLabel("Hello QT!");
QLabel *label = new QLabel("<h2><i>Hello</i>"
"<font color=red>Qt!</font></h>");
label->show();
return a.exec();
}
结果在上文
exitbutton
#include<QApplication>
#include<QPushButton>
int main_button(int argc,char*argv[]){
QApplication app(argc,argv);
QPushButton *button = new QPushButton("Quit");
QObject::connect(button,SIGNAL(clicked()),
&app,SLOT(quit()));
button->show();
return app.exec();
}
以上总结
先声明所需的窗口部件,然后再设置它们所应具备的属性,将这些窗口部件添加到布局中,布局会自动设置它们的位置和大小。利用Qt的信号和槽机理,并通过窗口部件之间的连接就可以管理用户的交互行为!