求助, qt 信号槽到底怎么传递 std::string 啊, SLOTS 始终调不到。

2020-03-05 13:13:46 +08:00
 fyyz

窗口 class 头文件是这么写的:

Q_DECLARE_METATYPE(std::string)

class A: public QMainWindow
{
	Q_OBJECT

	A()
	{
		qRegisterMetaType<std::string>("std::string");
		QObject::connect(
			this, SIGNAL(tunnel::add_item_into_table_signal(std::string, std::string, std::string)),
			this, SLOT(tunnel::add_item_into_table(std::string, std::string, std::string))
		);
	}

signals:
	// 这个函数的实现是由 Qmake 生成的,我能调试单步步进进去,看到实现里的代码跑到了
	void add_item_into_table_signal(std::string ip, std::string port, std::string remark);

public slots:
	void add_item_into_table(std::string ip, std::string port, std::string remark)
	{
		DebugBreak(); // 这里跑不到
	}
}

已经搞了一天了,我 emit 其他没有参数的信号函数都能跑到 slots,但是这个传了参数的函数就是跑不到 slots。

3291 次点击
所在节点    C++
12 条回复
YuxiangLuo
2020-03-05 13:20:12 +08:00
试试 QString 呢
fyyz
2020-03-05 13:30:17 +08:00
@YuxiangLuo 我更想知道我哪里不对,因为我看别人连自己的 struct 都能传递过去。
wbing
2020-03-05 13:36:51 +08:00
把"tunnel::" 去掉试试
ipwx
2020-03-05 13:36:56 +08:00
@fyyz Qt 的 type 要借助预编译器的吧。。。std::string 真的能被支持么?关键是用了 template。struct 等同于 class,qmake 至少支持 customized class。不过 qmake 对 template 支持极差我记得。
sc3263
2020-03-05 13:39:22 +08:00
QObject::connect(
this, SIGNAL(tunnel::add_item_into_table_signal(std::string, std::string, std::string)),
this, SLOT(tunnel::add_item_into_table(std::string, std::string, std::string))
);

去掉这边的 tunnel::
如果还不行的话,调试模式启动,看看 Qt 本身有没有输出类似
QObject::connect: No such signal A::add_item_into_table_signal(std::string, std::string, std::string) in xxx.cpp
的日志
sc3263
2020-03-05 13:39:47 +08:00
以及。。。2020 年了
fyyz
2020-03-05 13:39:59 +08:00
@wbing tunnel 就是 class A,刚刚复制黏贴代码后忘记改了。
sc3263
2020-03-05 13:40:42 +08:00
@sc3263 试一下 Qt5 里新的信号槽连接方式呗。那个会有编译期的类型检查。
fyyz
2020-03-05 13:45:10 +08:00
@sc3263 谢谢,用了函数指针就能找到了,以后我就这么写了~
vx2018
2020-03-05 13:46:24 +08:00
QObject::connect(this, &tunnel::add_item_into_table_signal, this, &tunnel::add_item_into_table);
这样不好吗? 非要用 SLOT 和 SIGNAL 宏.
ztcaoll222
2020-03-05 13:51:20 +08:00
我记得信号槽能发的类型是有限制的吧,自定义类要继承 QObject
https://doc.qt.io/qt-5/signalsandslots.html
dbskcnc
2020-03-06 10:12:26 +08:00
完成没问题的,不过需要多做点处理,
以下是正确答案:

一般在 main.cpp 里面加

qRegisterMetaType<std::string>();

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/650060

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX