QObject::connect
采用如下参数:
connect(const QtPrivate::FunctionPointer<Func1>::Object *sender, Func1 signal,
const QtPrivate::FunctionPointer<Func2>::Object *receiver, Func2 slot);
现在假设我正在创建一个方法 QPushButton *newPushButton(const QString &text, Func2 slot);
,我如何使用 Func2
作为参数类型,我必须包括一些东西吗?
这是我希望我的 newPushButton
看起来像的示例:
QPushButton *MyWidget::newPushButton(const QString &text, Func2 slot)
{
QPushButton *pushButton = new QPushButton(text);
layout->addWidget(pushButton);
QObject::connect(pushButton, &QPushButton::clicked,
this, slot);
return pushButton;
}
现在我可以这样调用它了:
MyWidget::MyWidget(QWidget *parent = 0) : QWidget(parent)
{
layout = new QVBoxLayout;
myButton1 = newPushButton("My Button One", &MyWidget::on_myButton1_clicked);
myButton2 = newPushButton("My Button Two", &MyWidget::on_myButton2_clicked);
setLayout(layout);
}
但是,我似乎无法弄清楚如何在不使用模板的情况下将 &MyWidget::slot
作为参数传递给 newPushButton()
方法(connect()
做到了吗?)。
layout
和两个 myButton
都是 MyWidget
的成员。
最佳答案
However, I can't seem to figure out how to pass &MyWidget::slot as a parameter to the newPushButton() method without using templates (how does connect() do it?).
我不明白——那些 connect() 重载使用模板:http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#212
你不能做同样的事情吗?
template<typename Func2>
QPushButton *MyWidget::newPushButton(const QString &text, Func2 slot)
{
QPushButton *pushButton = new QPushButton(text);
layout->addWidget(pushButton);
QObject::connect(pushButton, &QPushButton::clicked,
this, slot);
return pushButton;
}
关于c++ - QObject::connect 中 Func2 类型的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17449945/