小乌龟案例实现

Node创建

1. python环境配置

为clion添加python2的支持,具体可以参考前面的讲解

在新建的py文件开头添加环境说明:

#!/usr/bin/env python
#coding:utf-8

修改新建py文件的权限,添加可执行权限

chmod +x turtle_control.py

2. node源码编写

import rospy

if __name__ == '__main__':
    nodeName = "qt_turle_ctrl";
    # 创建ros node
    rospy.init_node(nodeName, anonymous=True)

Qt UI的创建

1. 窗体继承

class MainWindow1(QWidget):
    def __init__(self):
        super(MainWindow1, self).__init__()

2. 编写UI

# 设置title
self.setWindowTitle("小乌龟控制")
self.resize(400, 120)
# 设置布局
layout = QFormLayout()
self.setLayout(layout)
# 添加控件
self.editLinear = QLineEdit("0")
layout.addRow("线速度", self.editLinear)
self.editAngular = QLineEdit("0")
layout.addRow("角速度", self.editAngular)

self.btnSend = QPushButton("发送")
layout.addRow(self.btnSend)

3. 事件添加

# 添加事件
self.btnSend.clicked.connect(self.clickSend)

def clickSend(self):
    pass

4. Publisher整合

# 创建publisher
topicName = "/turtle1/cmd_vel"
self.publisher = rospy.Publisher(topicName, Twist, queue_size=1000)

5. 发送消息

# 创建消息
twist = Twist()
# 填充数据
twist.linear.x = linearX
twist.angular.z = angluarZ * math.pi / 180
# 发送消息
publisher.publish(twist)

完整示例代码

Window窗体

#!/usr/bin/env python
# coding: utf-8

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import rospy
from geometry_msgs.msg import Twist
from math import radians


class MainWindow(QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()

        # 设置title
        self.setWindowTitle("小乌龟控制")
        self.resize(400, 120)

        # 设置布局
        layout = QFormLayout()
        self.setLayout(layout)

        # 添加控件
        self.editLinear = QLineEdit("0")
        layout.addRow("线速度", self.editLinear)

        self.editAngular = QLineEdit("0")
        layout.addRow("角速度", self.editAngular)

        self.btnSend = QPushButton("发送")
        layout.addRow(self.btnSend)

        # 添加事件
        self.btnSend.clicked.connect(self.clickSend)

        # 创建publisher
        topicName = "/turtle1/cmd_vel"
        self.publisher = rospy.Publisher(topicName, Twist, queue_size=1000)

    def clickSend(self):
        linearX = float(self.editLinear.text())
        angularZ = radians(float(self.editAngular.text()))

        # 构建消息
        twist = Twist()
        twist.linear.x = linearX
        twist.angular.z = angularZ
        # 发布
        self.publisher.publish(twist)

#!/usr/bin/env python
# coding:utf-8

import sys
import rospy
from window import MainWindow
from PyQt5.QtWidgets import *

if __name__ == '__main__':
    nodeName = "turtle_ctrl1"
    rospy.init_node(nodeName)

    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()

    sys.exit(app.exec_())