在Qt的插槽中放置参数
Put arguments in slots in Qt
我创建了一个名为MyWindow的类,它继承了QWidget来创建一个窗口。下面是mywindow.h:
的内容class MyWindow: public QWidget{
public:
MyWindow(QString title,QString icon,int w = 600,int h = 400);
int getWidth() const;
int getHeight() const;
public slots:
void openDialogBox(QString title,QString message);
private:
int m_width;
int m_height;
};
有一个openDialogBox插槽,它以对话框的标题和消息作为参数。
我做了一个菜单栏,它看起来像这样:
MyWindow myWindow("Example window",QCoreApplication::applicationDirPath() + "/icon.png");
QMenuBar menuBar(&myWindow);
menuBar.setGeometry(0,0,myWindow.getWidth(),menuBar.geometry().height());
QMenu *fileMenu = new QMenu("&File");
QAction *fileMenu_open = fileMenu->addAction("&Open");
MyWindow::connect(fileMenu_open,&QAction::triggered,&myWindow,&MyWindow::openDialogBox);
在最后一行中,我想将参数发送到插槽&MyWindow::openDialogBox
。我试着做:
MyWindow::connect(fileMenu_open,&QAction::triggered,&myWindow,&MyWindow::openDialogBox("Title","Hello, this is a message"));
但是它不起作用(我不需要你解释为什么不起作用,我已经知道为什么了)。如何正确地做到这一点,使其发挥作用?
既然你正在使用新的信号槽语法,我建议使用c++11 lambda代替槽,并在槽内调用所需的函数,下面是你的连接调用的样子:
QObject::connect(fileMenu_open, &QAction::triggered, &myWindow, [&myWindow](){
myWindow.openDialogBox("Title","Hello, this is a message");
});
注意,openDialogBox
不需要是插槽,它可以是任何普通函数。
如果你的编译器不支持c++ 11 lambda表达式,你可能不得不声明一个不带任何参数的槽,并连接到那个槽。并在该槽内使用所需的参数调用函数…
使用lambdas
QObject::connect(fileMenu_open, &QAction::triggered, &myWindow, [QWeakPointer<MyWindow> weakWindow = myWindow]()
{
weakWindow->openDialogBox("Title","Hello, this is a message");
});
QWeakPointer在你的类被移动的情况下使用,所以"旧的"myWindow是一个悬空指针
如果你的类不会被移动,只需捕获myWindow。
注意,我的代码需要c++ 14在lambda捕获
相关文章:
- Qt5:连接:如果插槽的参数少于信号,如何使用"连接"
- Qt moveToThread,带有参数的信号/插槽
- 发生 Qt5.11 应用插件构建错误:信号和插槽参数不兼容
- Qt C++:静态断言失败:信号和插槽参数不兼容
- QMetaObject::invokeMethod的插槽参数
- 文档在哪里说明如果参数不是从末端删除参数,则无法从QT信号插槽连接中删除参数?
- 在插槽中传递多个参数
- 这是在Qt信号和插槽中使用参数调用函数的好方法吗?
- 在Qt信号和插槽中使用lambda语法并访问传递的参数
- 插槽(指向方法成员的指针)作为 SIP 中方法的参数
- Qt - 使用λ函数修改先前连接信号的插槽参数
- QTIMER,参数化插槽
- Qt信号和插槽:是复制的参考参数
- 将多个参数传递给插槽
- 插槽比信号提供的参数少,如何?-QT
- Qt 5将带有参数的插槽分配给QPushButton
- 将自定义参数传递到Qt/C++中的插槽
- 在 qt 中传递带有信号和插槽的参数
- Qt插槽参数已损坏
- Qt:从一个对象发出相同的信号,但参数不同;插槽通过接收的参数进行区分