C++ GUI Programming with Qt4 笔记 -- chap1

1. Hello Qt

#include <QApplication>
#include <QLabel>

int main(int argc, char *argv[]){

    QApplication app(argc, argv);
    QLabel *label = new QLabel("Hello, <h2><font color=red>Vivian</font></h2>!");
    label->show();
    return app.exec();
}

运行

qmake -project  // 生成 .pro
qmake  // 生成 Makefile
make  // 编译
./project_name  // 运行。生成的可执行程序以工程名(文件夹名)命名

  1. Qt 的库都以 Q 开头
  2. main 必须声明入参 argc, argv 并传递给 QApplication 实例。否则编译报错:对成员‘exec’的请求出现在‘app’中,而后者具有非类类型‘QApplication()’
  3. Qt 中,widget 即组件,比如 button, menus, scroll bars, and frames 等。
  4. Qt 中,widget 可以嵌套,任何 widget 都可以做 window,通常使用 QMainWindow or a QDialog
  5. Qt 内置 webkit 引擎,支持 html 显示。
  6. 不需要调用 delete 回收内存,因为内存泄漏很小,程序结束时操作系统会回收。

2. 事件处理 SIGNAL / SLOT

#include <QApplication>
#include <QPushButton>

int main(int argc, char *argv[]){

    QApplication app(argc, argv);
    QPushButton *btn= new QPushButton("Quit");
    QObject::connect(btn, SIGNAL(clicked()), &app, SLOT(quit()));
    btn->show();
    return app.exec();
}

Qt 的事件处理,使用 SIGNAL / SLOT 机制。

SIGNAL 与 SLAT 是 2 个宏,前者生成事件消息,后者响应事件消息。

connect 方法接受 4 个参数。源对象、事件,目标对象,处理方法。

3. 布局

与其他 GUI 一样,水平 / 垂直 / 格子 3 种布局方式

  • QHBoxLayout lays out widgets horizontally from left to right (right to left for some cultures).
  • QVBoxLayout lays out widgets vertically from top to bottom.
  • QGridLayout lays out widgets in a grid.

调用 setLayout 时,会把 layout 内已添加的节点设置为当前节点的字节点。

所以,如果一个节点要添加到 layout 中,则不需要指定 parent

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

int main(int argc, char *argv[]){

    QApplication app(argc, argv);
    QWidget *window = new QWidget;
    window->setWindowTitle("Enter your Age");

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

    QObject::connect(spinBox, SIGNAL(valueChanged(int)), slder, SLOT(setValue(int)));
    QObject::connect(slder, SIGNAL(valueChanged(int)), spinBox, SLOT(setValue(int)));

    spinBox->setValue(35);

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

    return app.exec();
}

4. Qt 库 class 继承关系

 

 

 

posted @ 2014-04-20 15:50  Jackon Yang  阅读(550)  评论(1编辑  收藏  举报