Qt 一个小例子

示例

信号和插槽用于对象之间的通信。信号和时隙机制是Qt的主要功能,可能是与其他框架提供的功能最大不同的部分。

最小的示例要求一个类具有一个信号,一个插槽和一个连接:

计数器

#ifndef COUNTER_H
#define COUNTER_H

#include <QWidget>
#include <QDebug>

class Counter : public QWidget
{
    /*
     * All classes that contain signals or slots must mention Q_OBJECT
     * at the top of their declaration.
     * They must also derive (directly or indirectly) from QObject.
     */
    Q_OBJECT

public:
    Counter (QWidget *parent = 0): QWidget(parent)
    {
            m_value = 0;

            /*
             * The most important line: connect the signal to the slot.
             */
            connect(this, &Counter::valueChanged, this, &Counter::printvalue);
    }

    void setValue(int value)
    {
        if (value != m_value) {
            m_value = value;
            /*
             * The emit line emits the signal valueChanged() from
             * the object, with the new value as argument.
             */
            emit valueChanged(m_value);
        }
    }

public slots:
    void printValue(int value)
    {
        qDebug() << "新值: " << value;
    }

signals:
    void valueChanged(int newValue);

private:
    int m_value;

};

#endif

在main设置新值。我们可以检查插槽的调用方式,并打印值。

#include <QtGui>
#include "counter.h"

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

    Counter counter;
    counter.setValue(10);
    counter.show();

    return app.exec();
}

最后,我们的项目文件:

SOURCES   = \
            main.cpp
HEADERS   = \
            counter.h