【问题标题】:How do I execute slot function without the object?如何在没有对象的情况下执行插槽功能?
【发布时间】:2018-01-16 12:29:24
【问题描述】:

我有一个带有一些按钮的 Qt 应用程序,当单击这些按钮时,它们会执行其各自的插槽功能。

现在我想自动执行一些槽函数,而不用点击。例如,这会执行 OK 操作:

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;
}

现在我想在 UIcommand 回调中自动执行 slot 函数,而不是在 main 函数中

//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;
  }

我怎样才能做到这一点?

【问题讨论】:

  • 使其在范围内或发出信号。
  • 您也可以创建插槽static 并直接调用它而不需要您的类的实例。但是,根据您使用的 Qt 版本,存在一些缺点,如此处所述stackoverflow.com/questions/9428038/…
  • 将插槽设为静态会导致许多编译错误(无法将成员函数声明为具有静态链接)。我认为发出信号是要做的事情,但我不知道该怎么做。如何在不访问 button_OK(它属于对话框对象)的情况下发出 button_OK SIGNAL(clicked())?
  • 我猜你已经在你的实现文件中添加了static 关键字,这就是你得到这个编译器错误的原因。当然,您还有 @SteakOverflow 已经描述的其他选项。
  • 您最好重新考虑您的类设计,将您想要执行的逻辑分离到一个QObject 派生类中,您始终可以独立于 UI 实例化。这将是一种干净的方式。

标签: c++ qt


【解决方案1】:

通常,带有回调的 API 提供一个 void * 以便您可以提供您的用户数据(您的 StartDialog 指针),如果不是这种情况并且您只有一个对话框对象,请使其在您的内部成为全局对象main,这样它就会对该函数可见。

C++11 方法也可以创建一个 lambda 作为回调函数来捕获对话框对象。

【讨论】:

    猜你喜欢
    • 2020-11-02
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多