首页 > 解决方案 > Qt 静态添加参数到连接指令

问题描述

我的代码如下所示:

connect(c_name, SIGNAL(stateChanged(int) ), employeesList, SLOT(changeVisibility(int)));

c_namea在哪里QCheckBox,我想将其连接stateChange到 中的属性的可见性employeesList,该方法如下所示:

void changeVisibility(int prop, int visibility){
        if(prop & EmployeeListElement::Name)
            updateVisibility(&EmployeeListElement::name, visibility);
        if(prop & EmployeeListElement::Surname)
            updateVisibility(&EmployeeListElement::surname, visibility);
        if(prop & EmployeeListElement::DateOfBirth)
            updateVisibility(&EmployeeListElement::date_of_birth, visibility);
        if(prop & EmployeeListElement::DateOfEmployment)
            updateVisibility(&EmployeeListElement::date_of_empl, visibility);

    }
private:
    void updateVisibility(QLabel* EmployeeListElement::* elem, int visibility){
        visibility ? (this->*elem)->show() : (this->*elem)->hide();
    }
...

如您所见,我需要传递第二个参数,即我所指的属性,所以我想做这样的事情:

connect(c_name, SIGNAL(stateChanged(int) ), employeesList, SLOT(changeVisibility(int, Class::first_enum_property)));

这不起作用,我的问题是,有没有办法做到这一点?也许没有使用SIGNALSLOT指令并使用一些(也许)lambdas?

标签: c++qtqt-signals

解决方案


使用 lambdas 确实应该可以解决您的问题:

connect(c_name, &QCheckBox::stateChanged, employeesList, [employeesList](int visibility){employeesList->changeVisibility(Class::first_enum_property, visibility);});

请注意,第三个参数(即上下文对象)是可选的,但对于在销毁时自动销毁连接很有用employeesList

参考


推荐阅读