信号与槽

来源:互联网 发布:超级记忆训练软件 编辑:程序博客网 时间:2024/05/21 11:31

继承自QObject的类中,除了c++的成员函数之外还有槽函数

槽函数可以通过代码手动调用,也可以通过信号调用

信号与槽的连接:

使用QObject的静态成员函数connect进行连接

bool QObject::connect ( const QObject * sender, const char * signal, const QObject * receiver, const char * method, Qt::ConnectionType type = Qt::AutoConnection ) [static]
Creates a connection of the given type from the signal in the sender object to the method in the receiver object. Returns true if the connection succeeds; otherwise returns false.

信号与槽的参数个数,类型顺序必须匹配

You must use the SIGNAL() and SLOT() macros when specifying the signal and the method, for example:
SIGNAL() and SLOT() 中的函数参数只写参数类型就行(如果有参数的话),不应该加形式参数

 QLabel *label = new QLabel;
 QScrollBar *scrollBar = new QScrollBar;
 QObject::connect(scrollBar, SIGNAL(valueChanged(int)),
                  label,  SLOT(setNum(int)));

自定义信号:

自定义信号时确保该类继承与QObject或其子类,在类声明中使用宏Q_OBJECT

定义信号时,只需写信号函数的声明,不需要定义,返回类型为void


class 类名:public QObject或其子类{

Q_OBJECT

//其他成员

signals:

void 信号名(参数);

};

发送信号:emit 信号函数


槽函数的定义和声明:

槽 函数不仅需要声明,而且需要定义(因为要有操作的实现)

class 类名:public QObject或其子类{

Q_OBJECT

//其他成员

public slots:    //public 或private 或protect

void 槽名(参数);

};



原创粉丝点击