gpt4 book ai didi

c++ - 为什么可以连接到未声明为 Q_SLOTS 的函数?

转载 作者:行者123 更新时间:2023-11-30 01:37:55 25 4
gpt4 key购买 nike

我“不小心”将信号连接到 QWidget::setToolTip():

bool ok = connect(source, &Source::textSignal, widget, &QWidget::setToolTip);
Q_ASSERT(ok);

... 它成功了。不仅连接成功,函数也被正确调用。

亲自尝试一下:
main.cpp

#include <QApplication>
#include <QLineEdit>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QLineEdit le;
bool ok = QObject::connect(&le, &QLineEdit::textChanged, &le, &QWidget::setToolTip);
Q_ASSERT(ok);
le.show();
return a.exec();
}

setToolTip() 未声明为 slot

来自 qwidget.h:

    // [...]
public Q_SLOTS: // start of Q_SLOTS
void setWindowTitle(const QString &);
#ifndef QT_NO_STYLE_STYLESHEET
void setStyleSheet(const QString& styleSheet);
#endif
public: // from my understanding, this should end the Q_SLOTS region
#ifndef QT_NO_STYLE_STYLESHEET
QString styleSheet() const;
#endif
QString windowTitle() const;
// [...]
bool isWindowModified() const;
#ifndef QT_NO_TOOLTIP
void setToolTip(const QString &); // no Q_SLOTS!?
QString toolTip() const;
void setToolTipDuration(int msec);
int toolTipDuration() const;
#endif

所以我想:这是不是因为toolTip被声明为Q_PROPERTY

    Q_PROPERTY(QString toolTip READ toolTip WRITE setToolTip)

文档没有提到这一点。

最佳答案

我在 woboq.com ('Connecting to any function' and preceding) 找到了答案:

[...]

class Test : public QObject
{ Q_OBJECT
public:
Test() {
connect(this, &Test::someSignal, this, &Test::someSlot);
}
signals:
void someSignal(const QString &);
public:
void someSlot(const QVariant &);
};

Connecting to any function

As you might have seen in the previous example, the slot was just declared as public and not as slot. Qt will indeed call directly the function pointer of the slot, and will not need moc introspection anymore. (It still needs it for the signal)

But what we can also do is connecting to any function or functor:

static void someFunction() {
qDebug() << "pressed";
}
// ... somewhere else
QObject::connect(button, &QPushButton::clicked, someFunction);

This can become very powerful when you associate that with boost or tr1::bind.

=> 函数指针无需声明为public slots:即可调用。

关于c++ - 为什么可以连接到未声明为 Q_SLOTS 的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48822547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com