使用下拉列表小部件时如何返回函数值

问题描述

我在Ubuntu上。在下拉列表中单击时,我需要返回一个函数,但不知道该怎么做。例如:

...
dropdownList.set_active_text("Choose");
dropdownList.signal_changed().connect(sigc::mem_fun(*this,&usb_boot::showing));
std::cout << "var = " << var << std::endl;
...

void usb_boot::showing(){

Gtk::MessageDialog dialogue(*this,dropdownList.get_active_text());
dialog.set_secondary_text("Choose list");
dialog.run();
std::cout << "You choose :\n" << dropdownList.get_active_row_number() << " " << dropdownList.get_active_text() << std::endl;

add return here ?

如何将dropdownList.get_active_text()dropdownList.get_active_row_number()返回给变量?

解决方法

如果我正确理解了您的问题,则希望重用从处理程序(即showing)范围内获得的一些值。为此,我建议使用lambda表达式并通过引用变量来捕获。例如:

#include <iostream>
#include <gtkmm.h>

int main(int argc,char **argv)
{
    auto app = Gtk::Application::create(argc,argv,"so.question.q63850579");
    
    Gtk::Window window;

    Gtk::ComboBoxText combo;
    combo.append("option 1");
    combo.append("option 2");
    combo.append("option 3");

    // These are your variables,which you want to set to the values the user will choose. They are defined
    // outise the handler:
    std::string choice;
    int row;

    // Here you set the handler. The variables 'choice','row' and 'combo' are all passed by reference to
    // the handler (notice the '&'):
    combo.signal_changed().connect([&choice,&row,&combo](){
        choice = combo.get_active_text();
        row = combo.get_active_row_number(); 

        // Inside the scope of the handler,we can see the variable content changing everytime the user
        // changes a value:
        std::cout << "Your current selection is item #" << row << ",which is: " << choice << std::endl;
    });

    window.add(combo);
    window.show_all();

    int returnCode = app->run(window);

    // When the window closes,the variables are read again,but this time from outside the handler's
    // scope. This is possible because they were references:
    std::cout << "Your final selection was item #" << row << ",which is: " << choice << std::endl;

    return returnCode;
}

由于使用了sigc::mem_fun,因此另一个选择是将内容保存在表示this所指向的对象的类的成员变量中。我个人更喜欢lambda表达式,因为这些值可能与类无关。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...