0

I have a Qt application with some buttons that, when clicked, execute its respective slot functions.

Now I want to automatically execute some of the slot functions, without clicking. So for example this does the OK action:

int main(int argc, char* argv[])
{
    MFCApplication app(argc, argv);


    StartDialog dialog;
    dialog.slot_function_OK_button(); //Automatically clicks OK button


    // initialise ROS and start spinning
    ros::init(argc, argv, "platero_ros");

    //ROS UI service
    ros::NodeHandle n;
    ros::ServiceServer service = n.advertiseService("UIservice", UIcommand);
    ROS_INFO("Ready to receive ROS messages to interact with UI.");    
    ros::AsyncSpinner spinner(1); // start ros loop
    spinner.start();



    dialog.show();
    return app.exec();


    return 0;
}

Now instead of in the main function, I want to automatically execute the slot functions in UIcommand callbacks

//rosui
bool UIcommand(project_ros::UIservice::Request  &req,
          project_ros::UIservice::Response &res)
  {
    res.response_string = std::string(req.ui_command.c_str())  + " command was received";

// I would like to do dialog.slot_function_OK_button() here but dialog is not in this scope

  ROS_INFO("%s", res.response_string.c_str());
  return true;
  }

How can I achieve that?

Daniel Viaño
  • 485
  • 1
  • 9
  • 26
  • 4
    Make it in scope or emit a signal. – SteakOverflow Jan 16 '18 at 12:46
  • 1
    You can also make the slot `static` and call it directly without an instance of your class. However there are some drawbacks depending on which Qt versions you are using as explained here https://stackoverflow.com/questions/9428038/is-it-possible-to-connect-a-signal-to-a-static-slot-without-a-receiver-instance – Fryz Jan 16 '18 at 14:32
  • Making the slot static leads to many compilation errors (cannot declare member function to have static linkage). I think emitting a signal is the thing to do, but I don't know how. How can I emit a button_OK SIGNAL (clicked()) without access to button_OK (It belongs to dialog object)? – Daniel Viaño Jan 16 '18 at 15:11
  • I guess you have add the `static` keyword in your implementation file, that's why you get this compiler error. Of course you have other options that @SteakOverflow already described. – Fryz Jan 16 '18 at 15:36
  • 1
    You better rethink your class design, separating the logic you want to execute into a `QObject` derived class you can always instantiate indepent from the UI. That would be the clean way to do it. – Murphy Jan 16 '18 at 16:10

1 Answers1

1

Usually API's with callbacks provide a void * so that you can provide your user data (your StartDialog pointer), if that's not the case and you only have a single dialog object make it global inside your main, that way it will be visible for that function.

A C++11 way would also be to create a lambda as your callback function capturing the dialog object.