Qt-如何在不兼容的信号和插槽之间使用连接
我正在尝试做一个游戏。在此我想调用一个函数,该函数将收到一个 point 。但这个函数应该由定时器的超时信号调用。谁能说一下如何实现这一目标。以下是所需/错误代码
Point p(a,b);
connect(timer,SIGNAL(timedout()),this,startDestruction(p));
有人能说一下如何实现这一点吗?
I am trying to do a game. In this I want to call a function, that function will receive a point . But this function should be invoked by a timer's timedout signal. Can anybody say how to achieve this. Below is the required/error code
Point p(a,b);
connect(timer,SIGNAL(timedout()),this,startDestruction(p));
Can anybody say how to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
你的设计有缺陷;
Your design is flawed;
您的问题通常可以通过使用
QSignalMapper
来解决,但这仅是支持QString
、int
、QWidget*
和QObject*
作为参数类型。如果您想使用其他类型,您需要实现自己的信号映射器(您不讨厌 Qt 不允许您创建从 QObject 派生的类模板吗?:),如下所示
: :
根据您的具体情况:
Your problem is usually solved by using
QSignalMapper
, but that only supportsQString
,int
,QWidget*
, andQObject*
as parameter types.If you want to use other types, you need to implement your own signal mapper (don't you hate how Qt doesn't let you make class templates derived from
QObject
s? :) like this:Usage:
In your specific case:
创建一个用作中间槽的方法,如下所示。
Create a method to use as an intermediate slot, like this.
您通常必须创建一个由计时器触发的中间槽,然后使用该点调用 startDestruction。
You usually have to create an intermediate slot that is triggered by the timer and then calls startDestruction with the point.
重新设计你的类怎么样,让 startDestruction() 成为 p 的一个槽。当 p.startDestruction() 被调用时,它会发出一个信号来通知主类。
How about redesign your class, so that startDestruction() is a slot of p. While p.startDestruction() is call, it'll emit a signal to notify the main class.
这是一个有效的、不那么简单的例子。
Qt 要求模拟的 QObject 派生类不在主文件中,这就是 Pipe 被分开的原因。使用对象作为包装器而不是函数可以提供更大的灵活性,并且不需要将变量封装在字段中(无需更改架构)。
输出
main.cpp
Game.h
Pipe.h
Here's working, not-so-minimal example.
Qt requires that the mocked QObject-derived class is not in the main file, and that's why Pipe is separated. Using object as the wrapper instead of a function gives greater flexibility and does not require you to encapsulate variable in a field (no architecture changes).
Output
main.cpp
Game.h
Pipe.h