在Qt的插槽中放置参数

Put arguments in slots in Qt

本文关键字:参数 插槽 Qt      更新时间:2023-10-16

我创建了一个名为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捕获

中声明一个变量