Qt 之 入门例程 (1)
下面以 “Hello Qt” 为例,简单介绍如何建立一个 Qt 工程 。
1 QLabel 例程
1.1 Hello Qt
#1 和 #2 表明包含的头文件; #6 创建一个 QApplication 类的实例对象,配合 #11 使整个程序开启事件循环;
#8 创建一个 QLabel 对象 label 并赋初值 “Hello Qt!”, 接着 #9 显示出该 label 对象。
1 #include <QApplication> 2 #include <QLabel> 3 4 int main(int argc, char *argv[]) 5 { 6 QApplication app(argc, argv); 7 8 QLabel label("Hello Qt!"); 9 label.show(); 10 11 return app.exec(); 12 }
工程配置文件 .pro 如下:
QT += core greaterThan(QT_MAJOR_VERSION, 4): QT += widgets CONFIG += c++11 TARGET = HelloQt TEMPLATE = app SOURCES += main.cpp
支持 HTML 风格
QLabel label("<h2><i>Hello</i>" "<font color=red>Qt!</font></h2>");
输出如下:
1.2 智能指针
在 <C++ GUI Programming with Qt4_2nd> 书中的例子是
8 QLabel *label = new QLabel("Hello Qt!"); 9 label->show();
因为程序小,关闭后操作系统会负责回收内存,但是这种 new 了之后不 delete 的方式是不推荐的。
1.2.1 Qt 的智能指针
如果非要使用指针,可以考虑 Qt 中的智能指针 QScopedPointer
QScopedPointer<QLabel> label(new QLabel("Hello Qt!"));
1.2.2 c++ 的智能指针
另一种解决方法, 是 c++ 中的智能指针 std::unique_ptr
std::unique_ptr<QLabel> label(new QLabel("Hello Qt!"));
注意包含头文件
#include <memory>
2 QPushButton 例程
下面例程使用了 QPushButton 类, 并通过 connect 函数将信号 clicked() 和槽函数 quit() 连接了起来。
当用户点击了按钮时, clicked() 信号被发出, 接着槽函数被自动执行,于是程序退出。
1 #include <QApplication> 2 #include <QPushButton> 3 4 int main(int argc, char *argv[]) 5 { 6 QApplication app(argc, argv); 7 8 QPushButton btn("Quit"); 9 QObject::connect(&btn, SIGNAL(clicked()), &app, SLOT(quit())); 10 btn.show(); 11 12 return app.exec(); 13 }
程序输出如下:
3 QSpinBox 和 QSlider
下面要实现如下界面,包含 spinbox 和 slider 两个控件,并且二者的数值互相关联。
#3 和 #4 包含所需头文件, #10 和 #11 建立一个窗口部件, #13 ~ #16 新建 spinbox 和 slider 控件对象,并且设置范围;
#18 和 #19 将二者连接起来, 使得 spinbox 和 slider 的数值保持实时同步;
#23 和 #24 将两个控件加入布的管理器 layout 中, #26 设置窗体部件的管理器为 layout, #27 显示出整个窗体部件。
1 #include <QApplication> 2 #include <QHBoxLayout> 3 #include <QSpinBox> 4 #include <QSlider> 5 6 int main(int argc, char *argv[]) 7 { 8 QApplication app(argc, argv); 9 10 QWidget window; 11 window.setWindowTitle("Enter Your Age"); 12 13 QSpinBox spin; 14 QSlider slider(Qt::Horizontal); 15 spin.setRange(0,130); 16 slider.setRange(0,130); 17 18 QObject::connect(&spin, SIGNAL(valueChanged(int)), &slider, SLOT(setValue(int))); 19 QObject::connect(&slider, SIGNAL(valueChanged(int)), &spin, SLOT(setValue(int))); 20 spin.setValue(35); 21 22 QHBoxLayout layout; 23 layout.addWidget(&spin); 24 layout.addWidget(&slider); 25 26 window.setLayout(&layout); 27 window.show(); 28 29 return app.exec(); 30 }
Qt 中有三个布局管理器类,分别是水平布局管理器 (QHBoxLayout), 垂直布局管理器 (QVBoxLayout), 以及网格布局管理器 (QGridLayout)
这些布局管理器,可以为加入其中的控件自动分配位置和尺寸大小,省却了手动布局画图的繁琐。
参考资料:
<C++ GUI Programming with Qt4_2nd> chapter 1
<Qt 学习之路2> 豆子 https://www.devbean.net/2012/08/qt-study-road-2-hello-world/