我正在使用 Qt,我目前正在尝试将 gui 上的按钮按下连接到静态函数。 Qt 中执行此操作的函数的语法为
connect(sender, &Sender::valueChanged, someFunction);
所以我的代码看起来像
QObject::connect(w.doneButton,&QPushButton::on_doneButton_pressed,getList);
问题是getList需要输入参数
QList<DeviceWidget*>* getList(Window w)
{
return w.getList();
}
如果我用 getList(w) 替换 getList,我会得到一个响应,说它无法处理 () 运算符。
'operator()' is not a member of 'QList<DeviceWidget*>*' return connect_functor(sender,signal,context,slot,&Func2::operator(),type);}
一定有办法解决这个问题。 Qt 设计者不会设置这样的限制,但我已经在互联网上搜索了几天,但似乎找不到任何东西。
感谢您的帮助!
最佳答案
(我的感觉是)解决问题的惯用方法是使用 boost::bind()
或 std::bind()
(如果你正如@Nim 在评论中所建议的那样,'正在使用 c++11)。
例如:
#include <boost/bind.hpp>
QObject::connect(w.doneButton, &QPushButton::on_doneButton_pressed, boost::bind(getList, w));
#include <functional>
QObject::connect(w.doneButton, &QPushButton::on_doneButton_pressed, std::bind(getList, w));
在 c++11 中,您还可以使用 lambda 函数(尽管 bind
更适合绑定(bind)参数):
QObject::connect(w.doneButton, &QPushButton::on_doneButton_pressed, [w]{ getList(w); });
如果你既不能使用 c++11 也不能使用 Boost,你可以退回到仿函数(这有点困惑,基本上是 lambda 在 c++11 中为你做的):
class getListProxy
{
public:
getListProxy(Window w) : m_w(w) {}
QList<DeviceWidget*>* operator()() {
return getList(m_w);
}
private:
Window m_w;
};
QObject::connect(w.doneButton, &QPushButton::on_doneButton_pressed, getListProxy(w));
另请注意,所有这些构造都将按值传递 w
,因为 getList(Window w)
按值获取 w
。根据 Window
的实现,这可能不是您想要的。
关于c++ - 输入不带括号的函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25245947/