【发布时间】:2019-01-31 15:57:35
【问题描述】:
我正在开发一个 C++ Qt GUI 来远程控制 ROS 机器人。我读过ros::spin() 命令应该在单独的线程中发出,所以我基本上拥有从QMainWindow 派生的常用MainWindow,其构造函数设置GUI 元素,使订阅者对象订阅它们各自的主题(例如@987654323 @ 代表sensor_msgs/Image 主题)并且还启动了另一个线程。为此,我从QThread 派生了一个“RosThread”类,它除了在调用RosThread::run() 时启动ros:MultiThreadedSpinner 之外什么都不做。
您可能会说,我在一般编程方面并不完全有经验,所以我的问题是,我的项目背后的基本概念是否对您有意义? 特别是我应该将 NodeHandle 和订阅者对象留在 MainWindow 中并从 MainWindow 构造函数设置订阅?
相关代码sn-ps:
主窗口.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();
}
【问题讨论】:
标签: c++ multithreading qt user-interface ros