[英]ROS-Qt GUI - How to distribute the Threads?
我正在使用C ++ Qt GUI来远程控制ROS机器人。 我读过ros::spin()
命令应该在单独的线程中发出,所以我基本上是从QMainWindow
派生出通常的MainWindow,它的构造函数设置了GUI元素,使Subscriber Objects订阅了它们各自的主题(例如image_transport::Subscriber
sensor_msgs/Image
主题的image_transport::Subscriber
),并启动另一个线程。 为此,我从QThread
派生了一个“ RosThread”类,该类除了在RosThread::run()
时启动ros:MultiThreadedSpinner
RosThread::run()
什么也不做。
正如您可能会说的那样,我通常对编程没有完全的经验,所以我的问题是,我的项目背后的基本概念对您有意义吗? 特别是我应该将NodeHandle和Subscriber对象留在MainWindow中,并从MainWindow构造函数中设置订阅吗?
相关代码段:
mainwindow.cpp:
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), itLeft(nh), itArm(nh)
{
//subscribe to cameras
imageSubLeft = itLeft.subscribe("/camera_1/image_raw", 1000, &MainWindow::camCallbackLeft, this);
imageSubArm = itArm.subscribe("/camera_2/image_raw", 1000, &MainWindow::camCallbackArm, this);
pagestack = new QStackedWidget;
page1 = new QWidget;
grid = new QGridLayout;
page1->setLayout(grid);
pagestack->addWidget(page1);
labelLeft = new QLabel;
labelMid = new QLabel;
grid->addWidget(labelLeft, 0, 0);
grid->addWidget(labelMid, 0, 1);
this->startSpinThread(); //starts the seperate Thread where run() is executed
this->setCentralWidget(pagestack);
this->setWindowState(Qt::WindowMaximized);
this->setMinimumSize(1024, 768);
}
MainWindow::~MainWindow(){}
void MainWindow::camCallbackLeft(const sensor_msgs::Image::ConstPtr &msg){/*some code*/}
void MainWindow::camCallbackArm(const sensor_msgs::Image::ConstPtr &msg){/*some code*/}
void MainWindow::closeEvent(QCloseEvent *event){/*some code*/}
void MainWindow::startSpinThread()
{
if(rosSpin.isRunning())
{
return;
}
//rosSpin is an Object of the of QThread derived class
rosSpin.start();
}
rosthread.h:
#ifndef ROSTHREAD_H
#define ROSTHREAD_H
#include <ros/ros.h>
#include <QThread>
class RosThread : public QThread
{
Q_OBJECT
public:
RosThread();
protected:
void run();
private:
ros::MultiThreadedSpinner spinner;
};
#endif // ROSTHREAD_H
rosthread.cpp:
#include "rosthread.h"
RosThread::RosThread()
{
}
void RosThread::run() {
spinner.spin();
}
main.cpp中:
#include "mainwindow.h"
#include <QApplication>
#include <ros/ros.h>
int main(int argc, char **argv)
{
ros::init(argc, argv, "gui_node");
QApplication app (argc, argv);
MainWindow *win = new MainWindow();
win->show();
return app.exec();
}
实际上,不打算以这种方式使用QThread。 看一下这篇博客文章和这个例子 。
但是无论如何,我建议使用标准的C ++线程。 添加std::unique_ptr<std::thread> thread;
到您的MainWindow类而不是RosThread
对象。 要启动线程,请使用thread.reset(new std::thread([](){ static ros::MultiThreadedSpinner spinner; spinner.spin(); });
智能指针std::unique_ptr
将自动删除线程对象,尽管您不要忘记在重置/销毁std::unique_ptr
对象之前使用std::thread::join()
或std::thread::detach()
另一解决方案是将ros::MultiThreadedSpinner
对象放入MainWindow类,并使用thread.reset(new std::thread(&ros::MultiThreadedSpinner::spin, spinner));
创建一个std::thread
。
我认为,应该将NodeHandle和Subscriber对象放到另一个类中,如果它们不直接属于MainWindow,则将该类的对象用作MainWindow的成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.