不带SLOT宏的Qt连接

Qt connect without SLOT macro

本文关键字:连接 Qt 宏的 SLOT 不带      更新时间:2023-10-16

假设我有一个包含"function()"的字符串,其中function()是类中的一个插槽,我想用任何信号连接该插槽,但要使用该字符串。两个

QString f="function()";
connect (randomobject, SIGNAL(randomsignal()), this, SLOT(f));
output: just says that slot f doesn't exist.

QString f="SLOT(function())";
//conversion to const char*
connect (randomobject, SIGNAL(randomsignal()), this, f);
output: Use the SLOT or SIGNAL macro to connect 

工作。

有没有类似的方法?重要的是它是一个字符串而不是函数指针。

您可以在qobjectdefs.h:中查看SLOT的定义

#ifndef QT_NO_DEBUG
# define SLOT(a)     qFlagLocation("1"#a QLOCATION)
# define SIGNAL(a)   qFlagLocation("2"#a QLOCATION)
#else
# define SLOT(a)     "1"#a
# define SIGNAL(a)   "2"#a
#endif

这意味着SLOT("func()")在预处理后简单地转换为"1func(()"。所以你可以写:

Test *t = new Test; // 'Test' class has slot void func()
QString str = "func()";
QPushButton *b = new QPushButton("pressme");
QObject::connect(b, SIGNAL(clicked()), t, QString("1" + str).toLatin1()); // toLatin1 converts QString to QByteArray

当您显示并按下按钮时,将调用Test中的slot func()。

请注意,"connect"将"const char*"作为第二个和第四个参数类型,因此必须将QString转换为"const char*"或"QByteArray"(将转换为char指针)。