Qt。是否可以在connect SLOT()中使用局部变量?
我希望mySlot在单击按钮时接收myVar。 有可能做那样的事吗?我不想在某个类中存储myVar指针 更新(我的解决方案):Qt。是否可以在connect SLOT()中使用局部变量?,qt,signals-slots,Qt,Signals Slots,我希望mySlot在单击按钮时接收myVar。 有可能做那样的事吗?我不想在某个类中存储myVar指针 更新(我的解决方案): void SomeClass::mySlot(MyClass *var){ ... } void SomeClass::SomeFunction(){ MyClass *myVar; QPushButton *button = new QPushButton(this); connect(button, SIGNAL(clicked()
void SomeClass::mySlot(MyClass *var){
...
}
void SomeClass::SomeFunction(){
MyClass *myVar;
QPushButton *button = new QPushButton(this);
connect(button, SIGNAL(clicked()), this, SLOT(mySlot(myVar)));
}
void SomeClass::mySlot(){
QPushButton*button=static_cast(sender());
MyClass*myVar=qobject_cast(qvariant_cast(按钮->属性(“myVar”));
...
}
void SomeClass::SomeFunction(){
MyClass*myVar;
QPushButton*按钮=新的QPushButton(此按钮);
按钮->设置属性(“myVar”,QVariant::fromValue((QObject*)myVar));
连接(按钮、信号(单击())、此、插槽(mySlot());
}
不,这是不可能的。您可以使用丢弃某些参数的插槽,但不能使用参数多于信号的插槽。另外,在连接插槽时不能传递变量 您可以使用(有关用法,请参见此处的示例)执行此操作,但需要非常小心使用对象生命周期
void SomeClass::mySlot(){
QPushButton *button = static_cast<QPushButton*>(sender());
MyClass *myVar = qobject_cast<MyClass*>(qvariant_cast<QObject *>(button->property("myVar")));
...
}
void SomeClass::SomeFunction(){
MyClass *myVar;
QPushButton *button = new QPushButton(this);
button->setProperty("myVar", QVariant::fromValue((QObject*)myVar));
connect(button, SIGNAL(clicked()), this, SLOT(mySlot()));
}
(注意,MyClass
需要从QObject
或QWidget
派生)
只要由myVar
指向的对象保持有效(即未被删除),这将起作用,但如果您不将指向该对象的指针存储在某个位置,则无法轻松删除它-因此可能会发生内存泄漏。(如果按住信号映射器和按钮指针,可以使用QSignalMapper
的mapping
成员恢复该对象)
另一方面,以下将不起作用:
QSignalMapper *signalMapper = new QSignalMapper(this);
MyClass *myVar = new ...;
QPushButton *button = new QPushButton(this);
connect(button, SIGNAL(clicked()), signalMapper, SLOT(map()));
signalMapper->setMapping(button, myVar);
connect(signalMapper, SIGNAL(mapped(MyClass*)),
this, SIGNAL(MySlot(MyClass*)));
这无法工作,因为在这种情况下,
myVar
引用的对象在someFunction
结束时被破坏,因此插槽将接收无效指针,这将导致未定义的行为(即,任何情况都可能发生-bug、崩溃、有时看似工作的事情不是其他事情,…).实际上,connect函数只是匹配函数调用的签名。这个答案并不正确。做@Eddie想做的事情是可能的——有一些限制,但这不是“不可能的”。很好的解决方案。但我决定使用以下命令:按钮->设置属性(“myVar”,QVariant::fromValue((QObject*)myVar));(在连接之前)MyClass*myVar=qobject_cast(qvariant_cast(static_cast(sender())->property(“myVar”);(在插槽中)您的解决方案不可能工作。connect
调用将失败。复制粘贴时我搞错了。我更正了连接
。谢谢你的评论!
QSignalMapper *signalMapper = new QSignalMapper(this);
MyClass myVar;
...
signalMapper->setMapping(button, &myVar); // WRONG
...