当前位置: 首页>>代码示例>>Python>>正文


Python QTimer.stop方法代码示例

本文整理汇总了Python中python_qt_binding.QtCore.QTimer.stop方法的典型用法代码示例。如果您正苦于以下问题:Python QTimer.stop方法的具体用法?Python QTimer.stop怎么用?Python QTimer.stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在python_qt_binding.QtCore.QTimer的用法示例。


在下文中一共展示了QTimer.stop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: MicoButtonsWidget

# 需要导入模块: from python_qt_binding.QtCore import QTimer [as 别名]
# 或者: from python_qt_binding.QtCore.QTimer import stop [as 别名]
class MicoButtonsWidget(QWidget):
    def __init__(self, widget):
        super(MicoButtonsWidget, self).__init__()
        rospkg_pack = rospkg.RosPack()
        ui_file = os.path.join(rospkg_pack.get_path('mico_controller'), 'resource', 'MicoButtons.ui')
        loadUi(ui_file, self)

        self.start_arm_srv = rospy.ServiceProxy('mico_arm_driver/in/start', MicoStart)
        self.stop_arm_srv = rospy.ServiceProxy('mico_arm_driver/in/stop', MicoStop)
        self.home_arm_srv = rospy.ServiceProxy('mico_arm_driver/in/home_arm', MicoHome)

        self._updateTimer = QTimer(self)
        self._updateTimer.timeout.connect(self.timeout_callback)

    def start(self):
        self._updateTimer.start(1000)  # loop rate[ms]

    def stop(self):
        self._updateTimer.stop()

    def timeout_callback(self):
        pass

    # rqt override
    def save_settings(self, plugin_settings, instance_settings):
        pass
        # instance_settings.set_value('topic_name', self._topic_name)

    def restore_settings(self, plugin_settings, instance_settings):
        pass
        # topic_name = instance_settings.value('topic_name')
        # try:
        # self._topic_name = eval(topic_name)
        # except Exception:
        # self._topic_name = self.TOPIC_NAME

    def shutdown_plugin(self):
        self.stop()

    @Slot()
    def on_qt_start_btn_clicked(self):
        rospy.loginfo(self.start_arm_srv())

    @Slot()
    def on_qt_stop_btn_clicked(self):
        rospy.loginfo(self.stop_arm_srv())

    @Slot()
    def on_qt_home_btn_clicked(self):
        rospy.loginfo(self.home_arm_srv())
开发者ID:mu-777,项目名称:mico_controller,代码行数:52,代码来源:mico_buttons_widget.py

示例2: TopicDataWidget

# 需要导入模块: from python_qt_binding.QtCore import QTimer [as 别名]
# 或者: from python_qt_binding.QtCore.QTimer import stop [as 别名]
class TopicDataWidget(QWidget):

	def __init__(self, widget):
		super(TopicDataWidget, self).__init__()
		rospkgPack = rospkg.RosPack()
		uiFile = os.path.join(rospkgPack.get_path('my_topic_viewer'), 'resource', 'TopicViewer.ui')
		loadUi(uiFile, self)

		self._updateTimer = QTimer(self)
		self._updateTimer.timeout.connect(self.timeoutCallback)

		self._widget = widget
		self._topicName = TOPIC_NAME
		self._subscriber = None

		self.subscribeTopic(self._topicName)

	def start(self):
		self._updateTimer.start(1000)

	def stop(self):
		self._updateTimer.stop()

	def timeoutCallback(self):
		pass
#		print 'time out'

	# rqt override
	def save_settings(self, plugin_settings, instance_settings):
		instance_settings.set_value('topic_name', self._topicName)

	def restore_settings(self, plugin_settings, instance_settings):
		topicName = instance_settings.value('topic_name')
		try:
			self._topicName = eval(topicName)
		except Exception:
			topicName = None

	def shutdown_plugin(self):
		self.unregisterTopic()
		self.stop()

	# subscribe topic
	def subscribeTopic(self, topicName):
#		msgClass, self._topicName, _ = get_topic_class(topicName)
		self._subscriber = rospy.Subscriber(TOPIC_NAME, MSG_CLASS, self.messageCallback)

	def messageCallback(self, msg):
		self.setDisplayedData(msg.data, TOPIC_NAME)

	def unregisterTopic(self):
		if self._subscriber:
			self._subscriber.unregister()

	def setDisplayedData(self, data, name):
		if isinstance(data, dict):
			self.displayData(data)
		else:
			dictData = {}
			if name is None:
				dictData['unknown'] = data
			elif isinstance(data, list):
				dictData = dict(zip(name, data))
			else:
				dictData[name] = data
			self.displayData(dictData)

	def displayData(self, dictData):
		for key in dictData.keys():
			self.topicLabel.setText(key+': ')
			self.topicDataLine.setText(str(dictData[key]))
开发者ID:my-garbage-collection,项目名称:rqt_test,代码行数:73,代码来源:topic_viewer_widget.py

示例3: TFBroadcasterWidget

# 需要导入模块: from python_qt_binding.QtCore import QTimer [as 别名]
# 或者: from python_qt_binding.QtCore.QTimer import stop [as 别名]
class TFBroadcasterWidget(QWidget):
    def __init__(self, widget):
        super(TFBroadcasterWidget, self).__init__()
        rospkg_pack = rospkg.RosPack()
        ui_file = os.path.join(rospkg_pack.get_path('gui_nodes'), 'resource', 'TFBroadcaster.ui')
        loadUi(ui_file, self)

        self._frame_id, self._child_frame_id = FRAME_ID, CHILD_FRAME_ID
        self._tf_manager = TFBroadcasterImpl(self._frame_id, self._child_frame_id)

        self.setup_ui()

        self._updateTimer = QTimer(self)
        self._updateTimer.timeout.connect(self.timeout_callback)

    def setup_ui(self):
        self._status_widget = StatusInputWidgetSet(self.qt_stop_radiobtn,
                                                   self.qt_static_tf_radiobtn,
                                                   self.qt_tf_radiobtn,
                                                   self._tf_manager.set_stop_status,
                                                   self._tf_manager.set_static_tf_status,
                                                   self._tf_manager.set_tf_status)

        self._frame_id_widget = FrameIDInputWidgetSet(self.qt_frame_id_lineedit,
                                                      self.qt_frame_id_update_btn,
                                                      self._frame_id,
                                                      self._tf_manager.set_frame_id)

        self._child_frame_id_widget = FrameIDInputWidgetSet(self.qt_child_frame_id_lineedit,
                                                            self.qt_child_frame_id_update_btn,
                                                            self._child_frame_id,
                                                            self._tf_manager.set_child_frame_id)

        self._x_widget = SliderSpinboxInputWidgetSet(self.qt_x_slider,
                                                     self.qt_x_spinbox,
                                                     self.qt_x_btn,
                                                     0.0, POS_MAX_VALUE, POS_MIN_VALUE)
        self._y_widget = SliderSpinboxInputWidgetSet(self.qt_y_slider,
                                                     self.qt_y_spinbox,
                                                     self.qt_y_btn,
                                                     0.0, POS_MAX_VALUE, POS_MIN_VALUE)
        self._z_widget = SliderSpinboxInputWidgetSet(self.qt_z_slider,
                                                     self.qt_z_spinbox,
                                                     self.qt_z_btn,
                                                     0.0, POS_MAX_VALUE, POS_MIN_VALUE)

        self._roll_widget = SliderSpinboxInputWidgetSet(self.qt_roll_slider,
                                                        self.qt_roll_spinbox,
                                                        self.qt_roll_btn,
                                                        0.0, ORI_MAX_VALUE, ORI_MIN_VALUE)
        self._pitch_widget = SliderSpinboxInputWidgetSet(self.qt_pitch_slider,
                                                         self.qt_pitch_spinbox,
                                                         self.qt_pitch_btn,
                                                         0.0, ORI_MAX_VALUE, ORI_MIN_VALUE)
        self._yaw_widget = SliderSpinboxInputWidgetSet(self.qt_yaw_slider,
                                                       self.qt_yaw_spinbox,
                                                       self.qt_yaw_btn,
                                                       0.0, ORI_MAX_VALUE, ORI_MIN_VALUE)


    def start(self):
        self._tf_manager.set_frames(self._frame_id, self._child_frame_id)
        self._updateTimer.start(10)  # loop rate[ms]

    def stop(self):
        self._updateTimer.stop()

    def timeout_callback(self):
        self._tf_manager.set_position(self._x_widget.value, self._y_widget.value, self._z_widget.value)
        self._tf_manager.set_orientation(self._roll_widget.value,
                                         self._pitch_widget.value,
                                         self._yaw_widget.value,
                                         is_rad=False)
        self._tf_manager.broadcast_tf()

    # override
    def save_settings(self, plugin_settings, instance_settings):
        self._frame_id = self._frame_id_widget.str
        self._child_frame_id = self._child_frame_id_widget.str
        instance_settings.set_value('frame_ids', (self._frame_id, self._child_frame_id))

    # override
    def restore_settings(self, plugin_settings, instance_settings):
        frames = instance_settings.value('frame_ids')
        try:
            self._frame_id, self._child_frame_id = frames
            self._frame_id_widget.update(self._frame_id)
            self._child_frame_id_widget.update(self._child_frame_id)
        except Exception:
            self._frame_id, self._child_frame_id = FRAME_ID, CHILD_FRAME_ID

    # override
    def shutdown_plugin(self):
        self.stop()
开发者ID:mu-777,项目名称:ez_tf_broadcaster,代码行数:96,代码来源:tf_broadcaster_widget.py

示例4: Top

# 需要导入模块: from python_qt_binding.QtCore import QTimer [as 别名]
# 或者: from python_qt_binding.QtCore.QTimer import stop [as 别名]

#.........这里部分代码省略.........
        self._toolbar = QToolBar()
        self._filter_box = QLineEdit()
        self._regex_box  = QCheckBox()
        self._regex_box.setText('regex')
        self._toolbar.addWidget(QLabel('Filter'))
        self._toolbar.addWidget(self._filter_box)
        self._toolbar.addWidget(self._regex_box)

        self._filter_box.returnPressed.connect(self.update_filter)
        self._regex_box.stateChanged.connect(self.update_filter)

        # Create a container widget and give it a layout
        self._container = QWidget()
        self._container.setWindowTitle('Process Monitor')
        self._layout    = QVBoxLayout()
        self._container.setLayout(self._layout)

        self._layout.addWidget(self._toolbar)

        # Create the table widget
        self._table_widget = QTreeWidget()
        self._table_widget.setObjectName('TopTable')
        self._table_widget.setColumnCount(len(self.NODE_LABELS))
        self._table_widget.setHeaderLabels(self.NODE_LABELS)
        self._table_widget.itemClicked.connect(self._tableItemClicked)
        self._table_widget.setSortingEnabled(True)
        self._table_widget.setAlternatingRowColors(True)

        self._layout.addWidget(self._table_widget)
        context.add_widget(self._container)

        # Add a button for killing nodes
        self._kill_button = QPushButton('Kill Node')
        self._layout.addWidget(self._kill_button)
        self._kill_button.clicked.connect(self._kill_node)

        # Update twice since the first cpu% lookup will always return 0
        self.update_table()
        self.update_table()

        self._table_widget.resizeColumnToContents(0)

        # Start a timer to trigger updates
        self._update_timer = QTimer()
        self._update_timer.setInterval(1000)
        self._update_timer.timeout.connect(self.update_table)
        self._update_timer.start()

    def _tableItemClicked(self, item, column):
        with self._selected_node_lock:
            self._selected_node = item.text(0)

    def update_filter(self, *args):
        if self._regex_box.isChecked():
            expr = self._filter_box.text()
        else:
            expr = re.escape(self._filter_box.text())
        self.name_filter = re.compile(expr)
        self.update_table()

    def _kill_node(self):
        self._node_info.kill_node(self._selected_node)

    def update_one_item(self, row, info):
        twi = TopWidgetItem()
        for col, field in enumerate(self.OUT_FIELDS):
            val = info[field]
            twi.setText(col, self.FORMAT_STRS[col] % val)
        self._table_widget.insertTopLevelItem(row, twi)

        for col, (key, func) in self.TOOLTIPS.iteritems():
            twi.setToolTip(col, func(info[key]))

        with self._selected_node_lock:
            if twi.text(0) == self._selected_node:
                twi.setSelected(True)

        self._table_widget.setItemHidden(twi, len(self.name_filter.findall(info['node_name'])) == 0)

    def update_table(self):
        self._table_widget.clear()
        infos = self._node_info.get_all_node_fields(self.NODE_FIELDS)
        for nx, info in enumerate(infos):
            self.update_one_item(nx, info)

    def shutdown_plugin(self):
        self._update_timer.stop()

    def save_settings(self, plugin_settings, instance_settings):        
        instance_settings.set_value('filter_text', self._filter_box.text())
        instance_settings.set_value('is_regex', int(self._regex_box.checkState()))

    def restore_settings(self, plugin_settings, instance_settings):
        self._filter_box.setText(instance_settings.value('filter_text'))
        is_regex_int = instance_settings.value('is_regex')
        if is_regex_int:
            self._regex_box.setCheckState(Qt.CheckState(is_regex_int))
        else:
            self._regex_box.setCheckState(Qt.CheckState(0))
        self.update_filter()
开发者ID:OSUrobotics,项目名称:rqt_common_plugins,代码行数:104,代码来源:top_plugin.py

示例5: Plot2DWidget

# 需要导入模块: from python_qt_binding.QtCore import QTimer [as 别名]
# 或者: from python_qt_binding.QtCore.QTimer import stop [as 别名]
class Plot2DWidget(QWidget):
    _redraw_interval = 40

    def __init__(self, topics):
        super(Plot2DWidget, self).__init__()
        self.setObjectName("Plot2DWidget")
        rp = rospkg.RosPack()
        ui_file = os.path.join(rp.get_path("jsk_rqt_plugins"), "resource", "plot_histogram.ui")
        loadUi(ui_file, self)
        self.cv_bridge = CvBridge()
        self.subscribe_topic_button.setIcon(QIcon.fromTheme("add"))
        self.pause_button.setIcon(QIcon.fromTheme("media-playback-pause"))
        self.clear_button.setIcon(QIcon.fromTheme("edit-clear"))
        self.data_plot = MatPlot2D(self)
        self.data_plot_layout.addWidget(self.data_plot)
        self._topic_completer = TopicCompleter(self.topic_edit)
        self._topic_completer.update_topics()
        self.topic_edit.setCompleter(self._topic_completer)
        self.data_plot.dropEvent = self.dropEvent
        self.data_plot.dragEnterEvent = self.dragEnterEvent
        self._start_time = rospy.get_time()
        self._rosdata = None
        if len(topics) != 0:
            self.subscribe_topic(topics)
        self._update_plot_timer = QTimer(self)
        self._update_plot_timer.timeout.connect(self.update_plot)
        self._update_plot_timer.start(self._redraw_interval)

    @Slot("QDropEvent*")
    def dropEvent(self, event):
        if event.mimeData().hasText():
            topic_name = str(event.mimeData().text())
        else:
            droped_item = event.source().selectedItems()[0]
            topic_name = str(droped_item.data(0, Qt.UserRole))
        self.subscribe_topic(topic_name)

    @Slot()
    def on_topic_edit_returnPressed(self):
        if self.subscribe_topic_button.isEnabled():
            self.subscribe_topic(str(self.topic_edit.text()))

    @Slot()
    def on_subscribe_topic_button_clicked(self):
        self.subscribe_topic(str(self.topic_edit.text()))

    def subscribe_topic(self, topic_name):
        self.topic_with_field_name = topic_name
        self.pub_image = rospy.Publisher(topic_name + "/histogram_image", Image)
        if not self._rosdata:
            self._rosdata = ROSData(topic_name, self._start_time)
        else:
            if self._rosdata != topic_name:
                self._rosdata.close()
                self.data_plot.clear()
                self._rosdata = ROSData(topic_name, self._start_time)
            else:
                rospy.logwarn("%s is already subscribed", topic_name)

    def enable_timer(self, enabled=True):
        if enabled:
            self._update_plot_timer.start(self._redraw_interval)
        else:
            self._update_plot_timer.stop()

    @Slot()
    def on_clear_button_clicked(self):
        self.data_plot.clear()

    @Slot(bool)
    def on_pause_button_clicked(self, checked):
        self.enable_timer(not checked)

    def update_plot(self):
        if not self._rosdata:
            return
        data_x, data_y = self._rosdata.next()

        if len(data_y) == 0:
            return
        axes = self.data_plot._canvas.axes
        axes.cla()
        # matplotlib
        # concatenate x and y in order to sort
        concatenated_data = zip(data_y[-1].xs, data_y[-1].ys)
        if self.sort_x:
            concatenated_data.sort(key=lambda x: x[0])
        xs = [d[0] for d in concatenated_data]
        ys = [d[1] for d in concatenated_data]
        if self.is_line:
            axes.plot(xs, ys, label=self.topic_with_field_name)
        else:
            axes.scatter(xs, ys)
        # set limit
        axes.set_xlim(min(xs), max(xs))
        axes.set_ylim(min(ys), max(ys))
        # line fitting
        if self.fit_line:
            X = np.array(data_y[-1].xs)
            Y = np.array(data_y[-1].ys)
#.........这里部分代码省略.........
开发者ID:DaikiMaekawa,项目名称:jsk_visualization,代码行数:103,代码来源:plot_2d.py

示例6: LifeFrame

# 需要导入模块: from python_qt_binding.QtCore import QTimer [as 别名]
# 或者: from python_qt_binding.QtCore.QTimer import stop [as 别名]
class LifeFrame(QFrame):
    STATE_STOPPED = "stopped"
    STATE_RUN = "running"
    STATE_IDLE = "idle"
    
    def __init__(self, parent=None):
        super(LifeFrame, self).__init__(parent)
        self._ui = Ui_life_frame()
        self._motion = Rotate('/mobile_base/commands/velocity')
        self._motion_thread = None
        self._timer = QTimer()
        #self._timer.setInterval(60000) #60s
        self._timer.setInterval(250) #60s
        QObject.connect(self._timer, SIGNAL('timeout()'), self, SLOT('update_progress_callback()'))
        self._state = LifeFrame.STATE_STOPPED
        self._is_alive = False # Used to indicate whether the frame is alive or not (see hibernate/restore methods)

    def setupUi(self):
        self._ui.setupUi(self)
        self._ui.start_button.setEnabled(True)
        self._ui.stop_button.setEnabled(False)
        self._motion.init(self._ui.angular_speed_spinbox.value())

    def shutdown(self):
        '''
          Used to terminate the plugin
        '''
        rospy.loginfo("Kobuki TestSuite: life frame shutdown")
        self._motion.shutdown()

    ##########################################################################
    # Widget Management
    ##########################################################################
        
    def hibernate(self):
        '''
          This gets called when the frame goes out of focus (tab switch). 
          Disable everything to avoid running N tabs in parallel when in
          reality we are only running one.
        '''
        pass
    
    def restore(self):
        '''
          Restore the frame after a hibernate.
        '''
        pass


    ##########################################################################
    # Motion Callbacks
    ##########################################################################

    def start(self):
        self._state = LifeFrame.STATE_RUN
        self._ui.run_progress.reset()
        self._ui.idle_progress.reset()
        self._motion_thread = WorkerThread(self._motion.execute, None)
        self._motion_thread.start()

    def stop(self):
        self._state = LifeFrame.STATE_STOPPED
        self._motion.stop()
        if self._motion_thread:
            self._motion_thread.wait()
        
    ##########################################################################
    # Qt Callbacks
    ##########################################################################
    @Slot()
    def on_start_button_clicked(self):
        self._ui.start_button.setEnabled(False)
        self._ui.stop_button.setEnabled(True)
        self._timer.start()
        self.start()
        
    @Slot()
    def on_stop_button_clicked(self):
        self.stop()
        self._timer.stop()
        self._ui.start_button.setEnabled(True)
        self._ui.stop_button.setEnabled(False)
        
    @pyqtSlot(float)
    def on_angular_speed_spinbox_valueChanged(self, value):
        self._motion.init(self._ui.angular_speed_spinbox.value())

    ##########################################################################
    # Timer Callbacks
    ##########################################################################

    @Slot()
    def update_progress_callback(self):
        if self._state == LifeFrame.STATE_RUN:
            new_value = self._ui.run_progress.value()+1
            if new_value == self._ui.run_progress.maximum():
                print("  Switching to idle")
                self._motion.stop()
                self._state = LifeFrame.STATE_IDLE
            else:
#.........这里部分代码省略.........
开发者ID:DaikiMaekawa,项目名称:kobuki_desktop,代码行数:103,代码来源:life_frame.py

示例7: Plot3DWidget

# 需要导入模块: from python_qt_binding.QtCore import QTimer [as 别名]
# 或者: from python_qt_binding.QtCore.QTimer import stop [as 别名]

#.........这里部分代码省略.........
        self.add_topic(topic_name)

    @Slot(str)
    def on_topic_edit_textChanged(self, topic_name):
        # on empty topic name, update topics
        if topic_name in ('', '/'):
            self._topic_completer.update_topics()

        is_numeric, is_array, message = is_slot_numeric(topic_name)
        self.subscribe_topic_button.setEnabled(is_numeric and not is_array)
        self.subscribe_topic_button.setToolTip(message)

    @Slot()
    def on_topic_edit_returnPressed(self):
        if self.subscribe_topic_button.isEnabled():
            self.add_topic(str(self.topic_edit.text()))

    @Slot()
    def on_subscribe_topic_button_clicked(self):
        self.add_topic(str(self.topic_edit.text()))

    @Slot(bool)
    def on_pause_button_clicked(self, checked):
        self.enable_timer(not checked)

    @Slot(bool)
    def on_autoscroll_checkbox_clicked(self, checked):
        self.data_plot.autoscroll(checked)

    @Slot()
    def on_clear_button_clicked(self):
        self.clean_up_subscribers()

    def update_plot(self):
        if self.data_plot is not None:
            needs_redraw = False
            for topic_name, rosdata in self._rosdata.items():
                try:
                    data_x, data_y = rosdata.next()
                    if data_x or data_y:
                        self.data_plot.update_values(topic_name, data_x, data_y)
                        needs_redraw = True
                except RosPlotException as e:
                    qWarning('PlotWidget.update_plot(): error in rosplot: %s' % e)
            if needs_redraw:
                self.data_plot.redraw()

    def _subscribed_topics_changed(self):
        self._update_remove_topic_menu()
        if not self.pause_button.isChecked():
            # if pause button is not pressed, enable timer based on subscribed topics
            self.enable_timer(self._rosdata)

    def _update_remove_topic_menu(self):
        def make_remove_topic_function(x):
            return lambda: self.remove_topic(x)

        self._remove_topic_menu.clear()
        for topic_name in sorted(self._rosdata.keys()):
            action = QAction(topic_name, self._remove_topic_menu)
            action.triggered.connect(make_remove_topic_function(topic_name))
            self._remove_topic_menu.addAction(action)

        self.remove_topic_button.setMenu(self._remove_topic_menu)

    def add_topic(self, topic_name):
        if topic_name in self._rosdata:
            qWarning('PlotWidget.add_topic(): topic already subscribed: %s' % topic_name)
            return

        self._rosdata[topic_name] = ROSData(topic_name, self._start_time)
        if self._rosdata[topic_name].error is not None:
            qWarning(str(self._rosdata[topic_name].error))
            del self._rosdata[topic_name]
        else:
            data_x, data_y = self._rosdata[topic_name].next()
            self.data_plot.add_curve(topic_name, topic_name, data_x, data_y)

            self._subscribed_topics_changed()

    def remove_topic(self, topic_name):
        self._rosdata[topic_name].close()
        del self._rosdata[topic_name]
        self.data_plot.remove_curve(topic_name)

        self._subscribed_topics_changed()

    def clean_up_subscribers(self):
        for topic_name, rosdata in self._rosdata.items():
            rosdata.close()
            self.data_plot.remove_curve(topic_name)
        self._rosdata = {}

        self._subscribed_topics_changed()

    def enable_timer(self, enabled=True):
        if enabled:
            self._update_plot_timer.start(self._redraw_interval)
        else:
            self._update_plot_timer.stop()
开发者ID:AtsushiSakai,项目名称:jsk_visualization,代码行数:104,代码来源:plot.py

示例8: ControllerManager

# 需要导入模块: from python_qt_binding.QtCore import QTimer [as 别名]
# 或者: from python_qt_binding.QtCore.QTimer import stop [as 别名]
class ControllerManager(Plugin):
    """
    Graphical frontend for managing ros_control controllers.
    """
    _cm_update_freq = 1  # Hz

    def __init__(self, context):
        super(ControllerManager, self).__init__(context)
        self.setObjectName('ControllerManager')

        # Create QWidget and extend it with all the attributes and children
        # from the UI file
        self._widget = QWidget()
        rp = rospkg.RosPack()
        ui_file = os.path.join(rp.get_path('rqt_controller_manager'),
                               'resource',
                               'controller_manager.ui')
        loadUi(ui_file, self._widget)
        self._widget.setObjectName('ControllerManagerUi')

        # Pop-up that displays controller information
        self._popup_widget = QWidget()
        ui_file = os.path.join(rp.get_path('rqt_controller_manager'),
                               'resource',
                               'controller_info.ui')
        loadUi(ui_file, self._popup_widget)
        self._popup_widget.setObjectName('ControllerInfoUi')

        # Show _widget.windowTitle on left-top of each plugin (when
        # it's set in _widget). This is useful when you open multiple
        # plugins at once. Also if you open multiple instances of your
        # plugin at once, these lines add number to make it easy to
        # tell from pane to pane.
        if context.serial_number() > 1:
            self._widget.setWindowTitle(self._widget.windowTitle() +
                                        (' (%d)' % context.serial_number()))
        # Add widget to the user interface
        context.add_widget(self._widget)

        # Initialize members
        self._cm_ns = []  # Namespace of the selected controller manager
        self._controllers = []  # State of each controller
        self._table_model = None
        self._controller_lister = None

        # Controller manager service proxies
        self._load_srv = None
        self._unload_srv = None
        self._switch_srv = None

        # Controller state icons
        rospack = rospkg.RosPack()
        path = rospack.get_path('rqt_controller_manager')
        self._icons = {'running': QIcon(path + '/resource/led_green.png'),
                       'stopped': QIcon(path + '/resource/led_red.png'),
                       'uninitialized': QIcon(path + '/resource/led_off.png')}

        # Controllers display
        table_view = self._widget.table_view
        table_view.setContextMenuPolicy(Qt.CustomContextMenu)
        table_view.customContextMenuRequested.connect(self._on_ctrl_menu)

        table_view.doubleClicked.connect(self._on_ctrl_info)

        header = table_view.horizontalHeader()
        header.setSectionResizeMode(QHeaderView.ResizeToContents)
        header.setContextMenuPolicy(Qt.CustomContextMenu)
        header.customContextMenuRequested.connect(self._on_header_menu)

        # Timer for controller manager updates
        self._list_cm = ControllerManagerLister()
        self._update_cm_list_timer = QTimer(self)
        self._update_cm_list_timer.setInterval(1000.0 /
                                               self._cm_update_freq)
        self._update_cm_list_timer.timeout.connect(self._update_cm_list)
        self._update_cm_list_timer.start()

        # Timer for running controller updates
        self._update_ctrl_list_timer = QTimer(self)
        self._update_ctrl_list_timer.setInterval(1000.0 /
                                                 self._cm_update_freq)
        self._update_ctrl_list_timer.timeout.connect(self._update_controllers)
        self._update_ctrl_list_timer.start()

        # Signal connections
        w = self._widget
        w.cm_combo.currentIndexChanged[str].connect(self._on_cm_change)

    def shutdown_plugin(self):
        self._update_cm_list_timer.stop()
        self._update_ctrl_list_timer.stop()
        self._popup_widget.hide()

    def save_settings(self, plugin_settings, instance_settings):
        instance_settings.set_value('cm_ns', self._cm_ns)

    def restore_settings(self, plugin_settings, instance_settings):
        # Restore last session's controller_manager, if present
        self._update_cm_list()
        cm_ns = instance_settings.value('cm_ns')
#.........这里部分代码省略.........
开发者ID:jinpyojeon,项目名称:TRIN_EARL,代码行数:103,代码来源:controller_manager.py

示例9: MainVirtJoy

# 需要导入模块: from python_qt_binding.QtCore import QTimer [as 别名]
# 或者: from python_qt_binding.QtCore.QTimer import stop [as 别名]
class MainVirtJoy(QWidget):
##########################################################################
##########################################################################

    #####################################################################    
    def __init__(self):
    #####################################################################    
        super(MainVirtJoy, self).__init__()
        self.timer_rate = rospy.get_param('~publish_rate', 150)
        self.pub_twist = rospy.Publisher('twist', Twist)
        
        self.x_min = rospy.get_param("~x_min", -0.10)
        self.x_max = rospy.get_param("~x_max", 0.10)
        self.r_min = rospy.get_param("~r_min", -1.0)
        self.r_max = rospy.get_param("~r_max", 1.0)
        
        self.timer = QTimer()
        self.timer.singleShot = False
        self.timer.timeout.connect(self.timerEvent)
        
   #####################################################################    
    def mousePressEvent(self, event):
    #####################################################################    
        rospy.logdebug('-D- virtual_joystick mouse clicked')
        self.timer.start(self.timer_rate)
        self.get_position(event)
        
    #####################################################################    
    def mouseReleaseEvent(self, event):
    #####################################################################    
        rospy.logdebug('-D- virtual_joystick mouse released')
        self.x = 0.5
        self.y = 0.5
        self.pubTwist()
        self.timer.stop()
        
    #####################################################################    
    def mouseMoveEvent(self, event):
    #####################################################################    
        self.get_position(event)
        
    #####################################################################    
    def get_position(self, event):
    #####################################################################    
        s = self.size()
        s_w = s.width()
        s_h = s.height()
        pos = event.pos()
        self.x = 1.0 * pos.x() / s_w
        self.y = 1.0 * pos.y() / s_h
        
        rospy.logdebug('-D- virtual_joystick point (%0.2f, %0.2f)' % (self.x,self.y))
        
    #####################################################################    
    def timerEvent(self):
    #####################################################################    
        rospy.logdebug("-D- virtual_joystick timer event")
        self.pubTwist()
        
    #######################################################
    def pubTwist(self):
    #######################################################
        # rospy.loginfo("publishing twist from (%0.3f,%0.3f)" %(self.x,self.y))
        self.twist = Twist()
        self.twist.linear.x = (1-self.y) * (self.x_max - self.x_min) + self.x_min
        self.twist.linear.y = 0
        self.twist.linear.z = 0
        self.twist.angular.x = 0
        self.twist.angular.y = 0
        self.twist.angular.z = (1-self.x) * (self.r_max - self.r_min) + self.r_min
        
        if self.twist.linear.x > self.x_max:
            self.twist.linear.x = self.x_max
        if self.twist.linear.x < self.x_min:
            self.twist.linear.x = self.x_min
        if self.twist.angular.z > self.r_max:
            self.twist.angular.z = self.r_max
        if self.twist.angular.z < self.r_min:
            self.twist.angular.z = self.r_min
        
        self.pub_twist.publish( self.twist )
开发者ID:jfstepha,项目名称:yertle-bot,代码行数:83,代码来源:virtual_joystick.py

示例10: Console

# 需要导入模块: from python_qt_binding.QtCore import QTimer [as 别名]
# 或者: from python_qt_binding.QtCore.QTimer import stop [as 别名]
class Console(Plugin):
    """
    rqt_console plugin's main class. Handles communication with ros_gui and contains
    callbacks to handle incoming message
    """
    def __init__(self, context):
        """
        :param context: plugin context hook to enable adding widgets as a ROS_GUI pane, ''PluginContext''
        """
        super(Console, self).__init__(context)
        self.setObjectName('Console')

        self._rospack = rospkg.RosPack()

        self._model = MessageDataModel()
        self._proxy_model = MessageProxyModel()
        self._proxy_model.setSourceModel(self._model)

        self._widget = ConsoleWidget(self._proxy_model, self._rospack)
        if context.serial_number() > 1:
            self._widget.setWindowTitle(self._widget.windowTitle() + (' (%d)' % context.serial_number()))
        context.add_widget(self._widget)

        # queue to store incoming data which get flushed periodically to the model
        # required since QSortProxyModel can not handle a high insert rate
        self._message_queue = []
        self._mutex = QMutex()
        self._timer = QTimer()
        self._timer.timeout.connect(self.insert_messages)
        self._timer.start(100)

        self._subscriber = None
        self._topic = '/rosout_agg'
        self._subscribe(self._topic)

    def queue_message(self, log_msg):
        """
        Callback for adding an incomming message to the queue.
        """
        if not self._widget._paused:
            msg = Console.convert_rosgraph_log_message(log_msg)
            with QMutexLocker(self._mutex):
                self._message_queue.append(msg)

    @staticmethod
    def convert_rosgraph_log_message(log_msg):
        msg = Message()
        msg.set_stamp_format('hh:mm:ss.ZZZ (yyyy-MM-dd)')
        msg.message = log_msg.msg
        msg.severity = log_msg.level
        msg.node = log_msg.name
        msg.stamp = (log_msg.header.stamp.secs, log_msg.header.stamp.nsecs)
        msg.topics = sorted(log_msg.topics)
        msg.location = log_msg.file + ':' + log_msg.function + ':' + str(log_msg.line)
        return msg

    def insert_messages(self):
        """
        Callback for flushing incoming Log messages from the queue to the model.
        """
        with QMutexLocker(self._mutex):
            msgs = self._message_queue
            self._message_queue = []
        if msgs:
            self._model.insert_rows(msgs)

    def shutdown_plugin(self):
        self._subscriber.unregister()
        self._timer.stop()
        self._widget.cleanup_browsers_on_close()

    def save_settings(self, plugin_settings, instance_settings):
        self._widget.save_settings(plugin_settings, instance_settings)

    def restore_settings(self, plugin_settings, instance_settings):
        self._widget.restore_settings(plugin_settings, instance_settings)

    def trigger_configuration(self):
        topics = [t for t in rospy.get_published_topics() if t[1] == 'rosgraph_msgs/Log']
        topics.sort(key=lambda tup: tup[0])
        dialog = ConsoleSettingsDialog(topics, self._rospack)
        (topic, message_limit) = dialog.query(self._topic, self._model.get_message_limit())
        if topic != self._topic:
            self._subscribe(topic)
        if message_limit != self._model.get_message_limit():
            self._model.set_message_limit(message_limit)

    def _subscribe(self, topic):
        if self._subscriber:
            self._subscriber.unregister()
        self._subscriber = rospy.Subscriber(topic, Log, self.queue_message)
        self._currenttopic = topic
开发者ID:OSUrobotics,项目名称:rqt_common_plugins,代码行数:94,代码来源:console.py

示例11: SysCheck

# 需要导入模块: from python_qt_binding.QtCore import QTimer [as 别名]
# 或者: from python_qt_binding.QtCore.QTimer import stop [as 别名]

#.........这里部分代码省略.........

        # Connect the valueChanged signal to our updateSpeed function
        self._widget.thrusterSpeed.valueChanged[int].connect(self.updateSpeed)

        self._widget.thrusterEnable.setCheckable(True)
        self._widget.thrusterEnable.toggled[bool].connect(self.enable)
        self._widget.thrusterKill.clicked[bool].connect(self.kill)

        # Load in the thruster buttons and connect callbacks
        self.thrusterButtons = []
        self.thrusterScales = []
        self.thrusterCallbacks = {}
        self.loadThrusters()

        # If the context is not the root add the serial number to the window
        #   title
        if context.serial_number() > 1:
            self._widget.setWindowTitle(self._widget.windowTitle() +
                                        (' (%d)' % context.serial_number()))

        # Add widget to the user interface
        context.add_widget(self._widget)

    def kill(self):
        for i in self.thrusterButtons:
            i.setChecked(False)
        self._widget.thrusterSpeed.setValue(0)


    def enable(self, s):
        if s:
            self.sendTimer.start(1000)
        else:
            self.sendTimer.stop()

    def loadThrusters(self):
        # Loop over all of the thruster values found in the params
        for i in range(0, len(self.names)):
            # Add a button to a list so we can mess with it later
            self.thrusterButtons.append(QPushButton(self.names[i]['name']))
            # Modify setting of the button
            self.thrusterButtons[i].setCheckable(True)

            # Save the callbacks in a list
            self.thrusterCallbacks[self.names[i]['name']] = \
                getattr(self, '_handle_thruster' + str(i))

            # Connect the callback to the button's toggle event
            self.thrusterButtons[i].toggled[bool].connect(
                    self.thrusterCallbacks[self.names[i]['name']])

            # Add the button to the Ui
            self._widget.thrusterButtons.addWidget(self.thrusterButtons[i])


            # Get the orientation
            self.thrusterScales.append(0)
            for v in self.names[i]['orientation'].values():
                self.thrusterScales[i] = self.thrusterScales[i] + v

            # Append a value to the thruster message for this button
            self.thrusterMessage.data.append(0.0)
        print self.thrusterScales

    def loadParam(self):
        try:
开发者ID:PalouseRobosub,项目名称:robosub,代码行数:70,代码来源:syscheck.py

示例12: Control

# 需要导入模块: from python_qt_binding.QtCore import QTimer [as 别名]
# 或者: from python_qt_binding.QtCore.QTimer import stop [as 别名]
class Control(Plugin):

    def __init__(self, context):
        super(Control, self).__init__(context)
        # Give QObjects reasonable names
        self.setObjectName('Control')

        # Create QWidget
        self._widget = QWidget()

        # Get path to UI file which should be in the "resource" folder of
        # this package
        ui_file = os.path.join(rospkg.RosPack().get_path('robosub'),
                               'src/rqt/rqt_control/resource', 'Control.ui')
        # Extend the widget with all attributes and children from UI file
        loadUi(ui_file, self._widget)

        self.control_timer = QTimer(self)
        self.control_timer.timeout.connect(self.control_missed)
        self.control_timer.start(1000)

        self.control_status_timer = QTimer(self)
        self.control_status_timer.timeout.connect(self.control_status_missed)
        self.control_status_timer.start(1000)

        # Give QObjects reasonable names
        self._widget.setObjectName('Control')

        if context.serial_number() > 1:
            self._widget.setWindowTitle(self._widget.windowTitle() +
                                        (' (%d)' % context.serial_number()))

        # Add widget to the user interface
        context.add_widget(self._widget)

        self._widget.statusActive.hide()
        self._widget.controlActive.hide()

        self.con_sub = rospy.Subscriber('control', control,
                                        self.control_callback, queue_size=1)
        self.cs_sub = rospy.Subscriber('control_status', control_status,
                                       self.control_status_callback,
                                       queue_size=1)
        img_file = os.path.join(rospkg.RosPack().get_path('robosub'),
                                'src/rqt/resource/robosub_logo.png')

        self._widget.setStyleSheet(".QWidget {background-image: url(" +
                                   img_file +
                                   "); background-repeat: no-repeat;" +
                                   "background-position:bottom right}")


    def control_missed(self):
        if not self._widget.controlStale.isVisible():
            self._widget.controlStale.show()
            self._widget.controlActive.hide()

    def control_status_missed(self):
        if not self._widget.statusStale.isVisible():
            self._widget.statusStale.show()
            self._widget.statusActive.hide()

    def control_status_callback(self, m):
        try:
            self.control_status_timer.stop()
        except RuntimeError:
            pass

        if self._widget.statusStale.isVisible():
            self._widget.statusStale.setVisible(False)
            self._widget.statusActive.setVisible(True)

        # Set the states
        self._widget.forwardStatusState.setText(m.forward_state)
        self._widget.strafeStatusState.setText(m.strafe_left_state)
        self._widget.diveStatusState.setText(m.dive_state)
        self._widget.rollStatusState.setText(m.roll_right_state)
        self._widget.pitchStatusState.setText(m.pitch_down_state)
        self._widget.yawStatusState.setText(m.yaw_left_state)

        self._widget.forwardGoal.setText("{:.4f}".format(m.forward_goal))
        self._widget.strafeGoal.setText("{:.4f}".format(m.strafe_left_goal))
        self._widget.diveGoal.setText("{:.4f}".format(m.dive_goal))
        self._widget.rollGoal.setText("{:.4f}".format(m.roll_right_goal))
        self._widget.pitchGoal.setText("{:.4f}".format(m.pitch_down_goal))
        self._widget.yawGoal.setText("{:.4f}".format(m.yaw_left_goal))
        self.control_status_timer.start(1000)

    def control_callback(self, m):
        try:
            self.control_timer.stop()
        except RuntimeError:
            pass

        if self._widget.controlStale.isVisible():
            self._widget.controlStale.hide()
            self._widget.controlActive.show()

        # Set the states
        self._widget.forwardState.setText(state_types[m.forward_state])
#.........这里部分代码省略.........
开发者ID:PalouseRobosub,项目名称:robosub,代码行数:103,代码来源:control.py

示例13: ConsoleDashWidget

# 需要导入模块: from python_qt_binding.QtCore import QTimer [as 别名]
# 或者: from python_qt_binding.QtCore.QTimer import stop [as 别名]

#.........这里部分代码省略.........
        self._timer = QTimer()
        self._timer.timeout.connect(self._insert_messages)
        self._timer.start(100)

        self._rospack = rospkg.RosPack()
        if self._console is None:
            self._console = ConsoleWidget(self._proxymodel, self._rospack, minimal=self.minimal)
            self._console.destroyed.connect(self._console_destroyed)
        self._console_shown = False
        self.setToolTip("Rosout")

    def _show_console(self):
        if self._console is None:
            self._console = ConsoleWidget(self._proxymodel, self._rospack, minimal=self.minimal)
            self._console.destroyed.connect(self._console_destroyed)
        try:
            if self._console_shown:
                self.context.remove_widget(self._console)
                self._console_shown = not self._console_shown
            else:
                self.context.add_widget(self._console)
                self._console_shown = not self._console_shown
        except Exception:
            self._console_shown = not self._console_shown
            self._show_console()

    def _insert_messages(self):
        with QMutexLocker(self._mutex):
            msgs = self._message_queue
            self._message_queue = []
        if msgs:
            self._datamodel.insert_rows(msgs)

        # The console may not yet be initialized or may have been closed
        # So fail silently
        try:
            self.update_rosout()
        except:
            pass

    def _message_cb(self, log_msg):
        if not self._console._paused:
            msg = Console.convert_rosgraph_log_message(log_msg)
            with QMutexLocker(self._mutex):
                self._message_queue.append(msg)

    def update_rosout(self):
        summary_dur = 30.0
        if (rospy.get_time() < 30.0):
            summary_dur = rospy.get_time() - 1.0

        if (summary_dur < 0):
            summary_dur = 0.0

        summary = self._console.get_message_summary(summary_dur)

        if (summary.fatal or summary.error):
            self.update_state(2)
        elif (summary.warn):
            self.update_state(1)
        else:
            self.update_state(0)

        tooltip = ""
        if (summary.fatal):
            tooltip += "\nFatal: %s" % (summary.fatal)
        if (summary.error):
            tooltip += "\nError: %s" % (summary.error)
        if (summary.warn):
            tooltip += "\nWarn: %s" % (summary.warn)
        if (summary.info):
            tooltip += "\nInfo: %s" % (summary.info)
        if (summary.debug):
            tooltip += "\nDebug: %s" % (summary.debug)

        if (len(tooltip) == 0):
            tooltip = "Rosout: no recent activity"
        else:
            tooltip = "Rosout: recent activity:" + tooltip

        if tooltip != self.toolTip():
            self.setToolTip(tooltip)

    def _console_destroyed(self):
        if self._console:
            self._console.cleanup_browsers_on_close()
        self._console = None

    def shutdown_widget(self):
        if self._console:
            self._console.cleanup_browsers_on_close()
        if self._subscriber:
            self._subscriber.unregister()
        self._timer.stop()

    def save_settings(self, plugin_settings, instance_settings):
        self._console.save_settings(plugin_settings, instance_settings)

    def restore_settings(self, plugin_settings, instance_settings):
        self._console.restore_settings(plugin_settings, instance_settings)
开发者ID:Aerobota,项目名称:rqt_robot_plugins,代码行数:104,代码来源:console_dash_widget.py

示例14: CopterPlugin

# 需要导入模块: from python_qt_binding.QtCore import QTimer [as 别名]
# 或者: from python_qt_binding.QtCore.QTimer import stop [as 别名]

#.........这里部分代码省略.........
        self._status_subscriber = rospy.Subscriber(status_topic, mav_status, self._status_subscriber_callback)

    def _state_subscriber_callback(self, input):
        if self.plot_start_time is -1:
            self.plot_start_time = input.header.stamp.to_sec()

        self.state_time = input.header.stamp.to_sec() - self.plot_start_time

        #if self.plot_position is not None:
        self.plot_position.update_value('x', self.state_time, input.state[0])
        self.plot_position.update_value('y', self.state_time, input.state[1])
        self.plot_position.update_value('z', self.state_time, input.state[2])

        #if self.plot_velocity is not None:
        self.plot_velocity.update_value('x', self.state_time, input.state[3])
        self.plot_velocity.update_value('y', self.state_time, input.state[4])
        self.plot_velocity.update_value('z', self.state_time, input.state[5])

        #if self.plot_acceleration_bias is not None:
        self.plot_acceleration_bias.update_value('x', self.state_time, input.state[6])
        self.plot_acceleration_bias.update_value('y', self.state_time, input.state[7])
        self.plot_acceleration_bias.update_value('z', self.state_time, input.state[8])

        #if self.plot_scale is not None:
        self.plot_scale.update_value('scale', self.state_time, input.state[9])

    def _status_subscriber_callback(self, input):
        self.status_time = input.header.stamp.to_sec() - self.plot_start_time
        self.voltage = input.battery_voltage
        self.cpu_load = input.cpu_load
        self.flight_mode_ll = input.flight_mode_ll
        self.state_estimation = input.state_estimation
        self.position_control = input.position_control
        self.motor_status = input.motor_status
        self.flight_time = input.flight_time
        self.gps_status = input.gps_status
        self.gps_num_satellites = input.gps_num_satellites

        #if self.plot_battery_voltage is not None:
        self.plot_battery_voltage.update_value('voltage', self.status_time, input.battery_voltage)

    def _create_plots(self):
        self.plot_start_time = -1

        self.plot_battery_voltage = QwtDataPlot(self._widget)
        self._widget.plot_battery_voltage_layout.addWidget(self.plot_battery_voltage)
        self.plot_battery_voltage.add_curve('voltage', 'Voltage', [0], [0])

        self.plot_position = QwtDataPlot(self._widget)
        self._widget.plot_position_layout.addWidget(self.plot_position)
        self.plot_position.add_curve('x', 'x-position', [0], [0])
        self.plot_position.add_curve('y', 'y-position', [0], [0])
        self.plot_position.add_curve('z', 'z-position', [0], [0])

        self.plot_velocity = QwtDataPlot(self._widget)
        self._widget.plot_velocity_layout.addWidget(self.plot_velocity)
        self.plot_velocity.add_curve('x', 'x-velocity', [0], [0])
        self.plot_velocity.add_curve('y', 'y-velocity', [0], [0])
        self.plot_velocity.add_curve('z', 'z-velocity', [0], [0])

        self.plot_acceleration_bias = QwtDataPlot(self._widget)
        self._widget.plot_acceleration_bias_layout.addWidget(self.plot_acceleration_bias)
        self.plot_acceleration_bias.add_curve('x', 'x-acc-bias', [0], [0])
        self.plot_acceleration_bias.add_curve('y', 'y-acc-bias', [0], [0])
        self.plot_acceleration_bias.add_curve('z', 'z-acc-bias', [0], [0])

        self.plot_scale = QwtDataPlot(self._widget)
        self._widget.plot_scale_layout.addWidget(self.plot_scale)
        self.plot_scale.add_curve('scale', 'visual scale', [0], [0])

    def _reset_plots(self):
        self._widget.plot_battery_voltage_layout.removeWidget(self.plot_battery_voltage)
        self.plot_battery_voltage.close()

        self._widget.plot_position_layout.removeWidget(self.plot_position)
        self.plot_position.close()

        self._widget.plot_velocity_layout.removeWidget(self.plot_velocity)
        self.plot_velocity.close()

        self._widget.plot_acceleration_bias_layout.removeWidget(self.plot_acceleration_bias)
        self.plot_acceleration_bias.close()

        self._widget.plot_scale_layout.removeWidget(self.plot_scale)
        self.plot_scale.close()

        self._create_plots()

    def shutdown_plugin(self):
        self._timer.stop()
        if self._state_subscriber is not None:
            self._state_subscriber.unregister()
        if self._status_subscriber is not None:
            self._status_subscriber.unregister()

    def save_settings(self, plugin_settings, instance_settings):
        pass

    def restore_settings(self, plugin_settings, instance_settings):
        pass
开发者ID:MorS25,项目名称:rqt_copter,代码行数:104,代码来源:rqt_copter.py

示例15: HistogramPlotWidget

# 需要导入模块: from python_qt_binding.QtCore import QTimer [as 别名]
# 或者: from python_qt_binding.QtCore.QTimer import stop [as 别名]
class HistogramPlotWidget(QWidget):
    _redraw_interval = 40
    def __init__(self, topics):
        super(HistogramPlotWidget, self).__init__()
        self.setObjectName('HistogramPlotWidget')
        rp = rospkg.RosPack()
        ui_file = os.path.join(rp.get_path('jsk_rqt_plugins'), 
                               'resource', 'plot_histogram.ui')
        loadUi(ui_file, self)
        self.subscribe_topic_button.setIcon(QIcon.fromTheme('add'))
        self.pause_button.setIcon(QIcon.fromTheme('media-playback-pause'))
        self.clear_button.setIcon(QIcon.fromTheme('edit-clear'))
        self.data_plot = MatHistogramPlot(self)
        self.data_plot_layout.addWidget(self.data_plot)
        self._topic_completer = TopicCompleter(self.topic_edit)
        self._topic_completer.update_topics()
        self.topic_edit.setCompleter(self._topic_completer)
        self.data_plot.dropEvent = self.dropEvent
        self.data_plot.dragEnterEvent = self.dragEnterEvent
        self._start_time = rospy.get_time()
        self._rosdata = None
        if len(topics) != 0:
            self.subscribe_topic(topics)
        self._update_plot_timer = QTimer(self)
        self._update_plot_timer.timeout.connect(self.update_plot)
        self._update_plot_timer.start(self._redraw_interval)
    @Slot('QDropEvent*')
    def dropEvent(self, event):
        print "hello"
        if event.mimeData().hasText():
            topic_name = str(event.mimeData().text())
        else:
            droped_item = event.source().selectedItems()[0]
            topic_name = str(droped_item.data(0, Qt.UserRole))
        self.subscribe_topic(topic_name)
    @Slot()
    def on_topic_edit_returnPressed(self):
        if self.subscribe_topic_button.isEnabled():
            self.subscribe_topic(str(self.topic_edit.text()))
    @Slot()
    def on_subscribe_topic_button_clicked(self):
        self.subscribe_topic(str(self.topic_edit.text()))

    def subscribe_topic(self, topic_name):
        if not self._rosdata:
            self._rosdata = ROSData(topic_name, self._start_time)
        else:
            if self._rosdata != topic_name:
                self._rosdata.close()
                self.data_plot.clear()
                self._rosdata = ROSData(topic_name, self._start_time)
            else:
                rospy.logwarn("%s is already subscribed", topic_name)
        
    def enable_timer(self, enabled=True):
        if enabled:
            self._update_plot_timer.start(self._redraw_interval)
        else:
            self._update_plot_timer.stop()
    @Slot()
    def on_clear_button_clicked(self):
        self.data_plot.clear()
    
    @Slot(bool)
    def on_pause_button_clicked(self, checked):
        self.enable_timer(not checked)
    
    def update_plot(self):
        if not self._rosdata:
            return
        data_x, data_y = self._rosdata.next()
        if len(data_y) == 0:
            return
        xs = data_y[-1]
        axes = self.data_plot._canvas.axes
        axes.cla()
        axes.set_xlim(xmin=0, xmax=len(xs))
        pos = np.arange(len(xs))
        #axes.xticks(range(5))
        for p, x in zip(pos, xs):
            axes.bar(p, x, color='r', align='center')
        self.data_plot._canvas.draw()
开发者ID:AtsushiSakai,项目名称:jsk_visualization,代码行数:84,代码来源:hist.py


注:本文中的python_qt_binding.QtCore.QTimer.stop方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。