【问题标题】:What is the difference connect(openAction, &QAction::triggered, ...) and connect(openAction, SIGNAL(triggered()) ...) in qtqt 中的 connect(openAction, &QAction::triggered, ...) 和 connect(openAction, SIGNAL(triggered()) ...) 有什么区别
【发布时间】:2021-06-13 12:56:55
【问题描述】:

我目前在qt中遇到了两种连接方式。

connect(openAction, &QAction::triggered, this, &MyMainWindow::openFile);
connect(openAction, SIGNAL(triggered()), this, SLOT(openFile()));

谁能指出差异以及何时使用哪个?

【问题讨论】:

  • 第二个是旧的信号/槽样式语法,第一个是新的。
  • 嗨,@chehrlic 我有一个问题。 QCombobox 有两个信号 void currentIndexChanged(int index);无效 currentIndexChanged(const QString &);当我使用新式连接时,它会显示模棱两可的编译错误。我看不到旧式的这个错误。有什么想法吗?
  • 那么您必须按照QComboBox::currentIndexChanged(int)的文档中的说明使用QOverload

标签: qt


【解决方案1】:

SIGNAL 表示函数的字符串表示,&QAction::triggered 是函数指针。 SIGNAL 是旧的做事方式,由于在运行时比较字符串比较慢。

以下代码行将解析为使用信号和槽的字符串比较的连接。

connect(this, SIGNAL(done(int)), this, SLOT(onDone(int)));

被调用的候选连接

    inline QMetaObject::Connection QObject::connect(
           const QObject *asender, const char *asignal,
           const char *amember, Qt::ConnectionType atype) const

函数指针版本将调用使用类型信息和函数地址的连接。

connect(this, &MainWindow::done, this, &MainWindow::onDone);

connect 的候选函数是众多采用成员函数指针的重载集之一。

//Connect a signal to a pointer to qobject member function
template <typename Func1, typename Func2>
static inline QMetaObject::Connection connect(
    const typename QtPrivate::FunctionPointer<Func1>::Object *sender, 
    Func1 signal,
    const typename QtPrivate::FunctionPointer<Func2>::Object *receiver, 
    Func2 slot,
    Qt::ConnectionType type = Qt::AutoConnection)

所以连接信号和槽的函数指针版本更快。

【讨论】:

  • 为我解释清楚。真的很感激。
  • 这些天来,开发人员还使用 SINGAL()、SLOT() 吗?或已弃用?我向你投了赞成票 :) 因为我从 3 个月前开始有一个大项目正在开发,我想知道我是否必须更换所有连接到新版本。
  • 一些老开发者使用SIGNAL和SLOT,但我更喜欢成员函数指针。它更快更明显。编译器可以检测成员函数指针版本中的错误,这在 SIGNAL 和 SLOT 中是不可能的。在 Qt 生态系统中,SIGNAL 和 SLOT 机制被称为旧的连接方式。所以我避免它。
  • 所以我是一个老开发者。我现在老了。呼~
  • 哈哈...我在开玩笑。但它通常由 5 到 10 年前从事开发的人完成,但现在他们不需要升级技能。当提供错误修复时,他们仍然使用 SIGNAL 和 SLOT。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-16
  • 1970-01-01
  • 2021-02-11
  • 2013-03-22
相关资源
最近更新 更多