Intro
用于处理两个节点时间通信的系统,将组件之间解耦
In GUI programming, when we change one widget, we often want another widget to be notified. More generally, we want objects of any kind to be able to communicate with one another. For example, if a user clicks a Close button, we probably want the window's close() function to be called.
Signal&Slots
使用emit signal(Arghs......)
,接受此信号的slot会被执行,slot可以时普通成员函数。
an Example:
#include <QObject>
class Counter : public QObject
{
Q_OBJECT
public:
Counter() { m_value = 0; }
int value() const { return m_value; }
public slots:
void setValue(int value);
signals:
void valueChanged(int newValue);
private:
int m_value;
};
void Counter::setValue(int value)
{
if (value != m_value) {
m_value = value;
emit valueChanged(value);
}
}
Counter a, b;
QObject::connect(&a, &Counter::valueChanged,
&b, &Counter::setValue);
a.setValue(12); // a.value() == 12, b.value() == 12
b.setValue(48); // a.value() == 12, b.value() == 48
这里
if (value != m_value) {
m_value = value;
emit valueChanged(value);
}
的意义是防止无限循环infinite looping
usage:
1.使用connect()函数
connect(const QObject sender, const char signal, const char *method, Qt::ConnectionType type = Qt::AutoConnection) const--QMetaObject::Connection
e.g:
void destroyed(QObject* = nullptr);
void objectDestroyed(QObject* obj = nullptr);
connect(sender, &QObject::destroyed, this, &MyObject::objectDestroyed);
也可以使用macros
connect(sender, SIGNAL(destroyed(QObject*)), this, SLOT(objectDestroyed(Qbject*)));
connect(sender, SIGNAL(destroyed(QObject*)), this, SLOT(objectDestroyed()));
connect(sender, SIGNAL(destroyed()), this, SLOT(objectDestroyed()));
注意:if the arguments have default values, is that the signature passed to the SIGNAL() macro must not have fewer arguments than the signature passed to the SLOT() macro.
当需要的slot需要传入者信息时建议用lamda
connect(action, &QAction::triggered, engine,
[=]() { engine->processAction(action->text()); });
与第三方库
target_compile_definitions(my_app PRIVATE QT_NO_KEYWORDS)
It tells Qt not to define the moc keywords signals
, slots
, and emit
, because these names will be used by a 3rd party library, e.g. Boost. Then to continue using Qt signals and slots with the no_keywords
flag, simply replace all uses of the Qt moc keywords in your sources with the corresponding Qt macros Q_SIGNALS (or Q_SIGNAL), Q_SLOTS (or Q_SLOT), and Q_EMIT.
评论区