Ejemplo n.º 1
0
def main():
    rospy.init_node('event_gui', anonymous=True)
    app = QApplication(sys.argv)
    event_gui = NodeWidgetsContainer()
    event_gui.show()
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    sys.exit(app.exec_())
Ejemplo n.º 2
0
 def create_application(self, argv):
     from python_qt_binding.QtCore import Qt
     from python_qt_binding.QtGui import QApplication
     # QApplication.setAttribute(Qt.AA_X11InitThreads, True)
     app = QApplication(argv)
     app.setAttribute(Qt.AA_DontShowIconsInMenus, False)
     return app
 def expandItem(self, path_item, path, item_id):
     '''
     Returns for the given item and path the file path if this is a file. Otherwise the
     folder will be expanded and None will be returned.
     @param path_item: the list item
     @type path_item: C{str}
     @param path: the real path of the item
     @type path: C{str}
     @return: path of the launch file or None
     @rtype: C{str}
     @raise Exception if no path to given item was found
     '''
     if path_item == '..':
         goto_path = os.path.dirname(path)
         key_mod = QApplication.keyboardModifiers()
         if key_mod & Qt.ControlModifier:
             goto_path = None
         root_path, items = self._moveUp(goto_path)
     elif os.path.isfile(path):
         return path
     elif item_id == LaunchItem.RECENT_FILE or item_id == LaunchItem.LAUNCH_FILE:
         raise Exception("Invalid file path: %s", path)
     else:
         key_mod = QApplication.keyboardModifiers()
         onestep = False
         if key_mod & Qt.ControlModifier:
             onestep = True
         root_path, items = self._moveDown(path, onestep)
     self._setNewList((root_path, items))
     return None
Ejemplo n.º 4
0
def main(name):
  try:
    from python_qt_binding.QtGui import QApplication
  except:
    print >> sys.stderr, "please install 'python_qt_binding' package!!"
    sys.exit(-1)

  masteruri = init_cfg_path()
  parser = init_arg_parser()
  args = rospy.myargv(argv=sys.argv)
  parsed_args = parser.parse_args(args[1:])
  # Initialize Qt
  global app
  app = QApplication(sys.argv)

  # decide to show main or echo dialog
  global main_form
  if parsed_args.echo:
    main_form = init_echo_dialog(name, masteruri, parsed_args.echo[0], parsed_args.echo[1], parsed_args.hz)
  else:
    main_form = init_main_window(name, masteruri, parsed_args.file)

  # resize and show the qt window
  if not rospy.is_shutdown():
    os.chdir(PACKAGE_DIR) # change path to be able to the images of descriptions
    main_form.resize(1024, 720)
    screen_size = QApplication.desktop().availableGeometry()
    if main_form.size().width() >= screen_size.width() or main_form.size().height() >= screen_size.height()-24:
      main_form.showMaximized()
    else:
      main_form.show()
    exit_code = -1
    rospy.on_shutdown(finish)
    exit_code = app.exec_()
Ejemplo n.º 5
0
 def on_ros_shutdown(self, *args):
     try:
         from python_qt_binding.QtGui import QApplication
         QApplication.exit(0)
     except Exception:
         from python_qt_binding.QtWidgets import QApplication
         QApplication.exit(0)
Ejemplo n.º 6
0
 def on_launch_selection_activated(self, activated):
     '''
     Tries to load the launch file, if one was activated.
     '''
     selected = self._launchItemsFromIndexes(self.xmlFileView.selectionModel().selectedIndexes(), False)
     for item in selected:
         try:
             lfile = self.launchlist_model.expandItem(item.name, item.path, item.id)
             self.searchPackageLine.setText('')
             if lfile is not None:
                 if item.isLaunchFile():
                     nm.settings().launch_history_add(item.path)
                     key_mod = QApplication.keyboardModifiers()
                     if key_mod & Qt.ShiftModifier:
                         self.load_as_default_signal.emit(item.path, None)
                     elif key_mod & Qt.ControlModifier:
                         self.launchlist_model.setPath(os.path.dirname(item.path))
                     else:
                         self.load_signal.emit(item.path, [], None)
                 elif item.isProfileFile():
                     nm.settings().launch_history_add(item.path)
                     key_mod = QApplication.keyboardModifiers()
                     if key_mod & Qt.ControlModifier:
                         self.launchlist_model.setPath(os.path.dirname(item.path))
                     else:
                         self.load_profile_signal.emit(item.path)
                 elif item.isConfigFile():
                     self.edit_signal.emit([lfile])
         except Exception as e:
             rospy.logwarn("Error while load launch file %s: %s" % (item, e))
             WarningMessageBox(QMessageBox.Warning, "Load error",
                               'Error while load launch file:\n%s' % item.name,
                               "%s" % e).exec_()
Ejemplo n.º 7
0
 def expandItem(self, path_item, path, item_id):
     '''
     Returns for the given item and path the file path if this is a file. Otherwise the
     folder will be expanded and None will be returned.
     @param path_item: the list item
     @type path_item: C{str}
     @param path: the real path of the item
     @type path: C{str}
     @return: path of the launch file or None
     @rtype: C{str}
     @raise Exception if no path to given item was found
     '''
     if path_item == '..':
         goto_path = os.path.dirname(path)
         key_mod = QApplication.keyboardModifiers()
         if key_mod & Qt.ControlModifier:
             goto_path = None
         root_path, items = self._moveUp(goto_path)
     elif os.path.isfile(path):
         return path
     elif item_id == LaunchItem.RECENT_FILE or item_id == LaunchItem.LAUNCH_FILE:
         raise Exception("Invalid file path: %s", path)
     else:
         key_mod = QApplication.keyboardModifiers()
         onestep = False
         if key_mod & Qt.ControlModifier:
             onestep = True
         root_path, items = self._moveDown(path, onestep)
     self._setNewList((root_path, items))
     return None
Ejemplo n.º 8
0
def main():
    app = QApplication(sys.argv)
    
    test_g = MainWidget()
    test_g.show()
    
    return app.exec_()
 def on_launch_selection_activated(self, activated):
     '''
     Tries to load the launch file, if one was activated.
     '''
     selected = self._launchItemsFromIndexes(self.xmlFileView.selectionModel().selectedIndexes(), False)
     for item in selected:
         try:
             lfile = self.launchlist_model.expandItem(item.name, item.path, item.id)
             self.searchPackageLine.setText('')
             if lfile is not None:
                 if item.isLaunchFile():
                     nm.settings().launch_history_add(item.path)
                     key_mod = QApplication.keyboardModifiers()
                     if key_mod & Qt.ShiftModifier:
                         self.load_as_default_signal.emit(item.path, None)
                     elif key_mod & Qt.ControlModifier:
                         self.launchlist_model.setPath(os.path.dirname(item.path))
                     else:
                         self.load_signal.emit(item.path, [], None)
                 elif item.isProfileFile():
                     nm.settings().launch_history_add(item.path)
                     key_mod = QApplication.keyboardModifiers()
                     if key_mod & Qt.ControlModifier:
                         self.launchlist_model.setPath(os.path.dirname(item.path))
                     else:
                         self.load_profile_signal.emit(item.path)
                 elif item.isConfigFile():
                     self.edit_signal.emit([lfile])
         except Exception as e:
             rospy.logwarn("Error while load launch file %s: %s" % (item, utf8(e)))
             MessageBox.warning(self, "Load error",
                                'Error while load launch file:\n%s' % item.name,
                                "%s" % utf8(e))
Ejemplo n.º 10
0
def main(name):
    '''
    Start the NodeManager or EchoDialog.
    :param name: the name propagated to the rospy.init_node()
    :type name: str
    '''
    try:
        from python_qt_binding.QtGui import QApplication
    except:
        try:
            from python_qt_binding.QtWidgets import QApplication
        except:
            print >> sys.stderr, "please install 'python_qt_binding' package!!"
            sys.exit(-1)

    init_settings()
    detect_version()
    parser = init_arg_parser()
    args = rospy.myargv(argv=sys.argv)
    parsed_args = parser.parse_args(args[1:])
    if parsed_args.muri:
        masteruri = parsed_args.muri[0]
        hostname = NameResolution.get_ros_hostname(masteruri)
        os.environ['ROS_MASTER_URI'] = masteruri
        if hostname:
            os.environ['ROS_HOSTNAME'] = hostname
    masteruri = settings().masteruri()
    # Initialize Qt
    global _QAPP
    _QAPP = QApplication(sys.argv)

    # decide to show main or echo dialog
    global _MAIN_FORM
    try:
        if parsed_args.echo:
            _MAIN_FORM = init_echo_dialog(name, masteruri, parsed_args.echo[0],
                                          parsed_args.echo[1], parsed_args.hz,
                                          parsed_args.ssh)
        else:
            _MAIN_FORM = init_main_window(name, masteruri, parsed_args.file)
    except Exception as err:
        sys.exit("%s" % err)

    exit_code = 0
    # resize and show the qt window
    if not rospy.is_shutdown():
        # change path for access to the images of descriptions
        os.chdir(settings().PACKAGE_DIR)
        #    _MAIN_FORM.resize(1024, 720)
        screen_size = QApplication.desktop().availableGeometry()
        if (_MAIN_FORM.size().width() >= screen_size.width()
                or _MAIN_FORM.size().height() >= screen_size.height() - 24):
            _MAIN_FORM.showMaximized()
        else:
            _MAIN_FORM.show()
        exit_code = -1
        rospy.on_shutdown(finish)
        exit_code = _QAPP.exec_()
    return exit_code
Ejemplo n.º 11
0
 def __init__(self, rqt_plugin_name):
     signal.signal(signal.SIGINT, self._shutdown)
     self._app = QApplication(sys.argv)
     self._rqt_wrapper = Switcher(rqt_plugin_name)
     # Let the interpreter run each 200 ms, this gives a chance for CTRL-C signals to come through
     self._give_signals_a_chance_timer = QTimer()
     self._give_signals_a_chance_timer.timeout.connect(lambda: None)
     self._give_signals_a_chance_timer.start(200)
Ejemplo n.º 12
0
 def __init__(self, img):
     splash_pix = QPixmap(img)
     self.splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
     self.splash.setMask(splash_pix.mask())
     self.splash.show()
     for i in range(100):
         time.sleep(0.01)
         QApplication.processEvents()
Ejemplo n.º 13
0
 def __init__(self, img):
     splash_pix = QPixmap(img)
     self.splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
     self.splash.setMask(splash_pix.mask())
     self.splash.show()
     for i in range(100):
         time.sleep(0.01)
         QApplication.processEvents()
Ejemplo n.º 14
0
def main(name):
    '''
    Start the NodeManager or EchoDialog.
    :param name: the name propagated to the rospy.init_node()
    :type name: str
    '''
    try:
        from python_qt_binding.QtGui import QApplication
    except:
        try:
            from python_qt_binding.QtWidgets import QApplication
        except:
            print >> sys.stderr, "please install 'python_qt_binding' package!!"
            sys.exit(-1)

    init_settings()
    parser = init_arg_parser()
    args = rospy.myargv(argv=sys.argv)
    parsed_args = parser.parse_args(args[1:])
    if parsed_args.muri:
        masteruri = parsed_args.muri[0]
        hostname = NameResolution.get_ros_hostname(masteruri)
        os.environ['ROS_MASTER_URI'] = masteruri
        if hostname:
            os.environ['ROS_HOSTNAME'] = hostname
    masteruri = settings().masteruri()
    # Initialize Qt
    global _QAPP
    _QAPP = QApplication(sys.argv)

    # decide to show main or echo dialog
    global _MAIN_FORM
    try:
        if parsed_args.echo:
            _MAIN_FORM = init_echo_dialog(name, masteruri, parsed_args.echo[0],
                                          parsed_args.echo[1], parsed_args.hz,
                                          parsed_args.ssh)
        else:
            _MAIN_FORM = init_main_window(name, masteruri, parsed_args.file)
    except Exception as err:
        sys.exit("%s" % err)

    exit_code = 0
    # resize and show the qt window
    if not rospy.is_shutdown():
        # change path for access to the images of descriptions
        os.chdir(settings().PACKAGE_DIR)
#    _MAIN_FORM.resize(1024, 720)
        screen_size = QApplication.desktop().availableGeometry()
        if (_MAIN_FORM.size().width() >= screen_size.width() or
                _MAIN_FORM.size().height() >= screen_size.height() - 24):
            _MAIN_FORM.showMaximized()
        else:
            _MAIN_FORM.show()
        exit_code = -1
        rospy.on_shutdown(finish)
        exit_code = _QAPP.exec_()
    return exit_code
 def copy_to_clipboard(self, indexes):
     '''
     Copy the selected path to the clipboard
     '''
     mimeData = QMimeData()
     text = ''
     for index in indexes:
         if index.isValid():
             item = self.itemFromIndex(index)
             prev = '%s\n' % text if text else ''
             text = '%sfile://%s' % (prev, item.path)
     mimeData.setData('text/plain', text.encode('utf-8'))
     QApplication.clipboard().setMimeData(mimeData)
Ejemplo n.º 16
0
 def copy_to_clipboard(self, indexes):
     '''
     Copy the selected path to the clipboard.
     '''
     mimeData = QMimeData()
     text = ''
     for index in indexes:
         if index.isValid():
             item = self.itemFromIndex(index)
             prev = '%s\n' % text if text else ''
             text = '%s%s' % (prev, item.path)
     mimeData.setData('text/plain', text.encode('utf-8'))
     QApplication.clipboard().setMimeData(mimeData)
Ejemplo n.º 17
0
    def paint(self, painter, option, index):
        if index.column() in [0,3]:
            return super(GroupsDelegate, self).paint(painter, option, index)

        button = QStyleOptionButton()
        r = option.rect
        x = r.left() + r.width() - 30
        y = r.top()+ 2
        w = 28
        h = 14
        button.rect = QRect(x,y,w,h)
        button.text = '+' if index.column() == 1 else '-'
        button.state = QStyle.State_Enabled

        QApplication.style().drawControl(QStyle.CE_PushButton, button, painter)
Ejemplo n.º 18
0
 def closeEvent(self, event):
     if self.sub is not None:
         self.sub.unregister()
         del self.sub
     try:
         self.ssh_output_file.close()
         self.ssh_error_file.close()
         # send Ctrl+C to remote process
         self.ssh_input_file.write("%s\n" % chr(3))
         self.ssh_input_file.close()
     except:
         pass
     self.finished_signal.emit(self.topic)
     if self.parent() is None:
         QApplication.quit()
Ejemplo n.º 19
0
    def paint(self, painter, option, index):
        if index.column() in [0, 3]:
            return super(GroupsDelegate, self).paint(painter, option, index)

        button = QStyleOptionButton()
        r = option.rect
        x = r.left() + r.width() - 30
        y = r.top() + 2
        w = 28
        h = 14
        button.rect = QRect(x, y, w, h)
        button.text = '+' if index.column() == 1 else '-'
        button.state = QStyle.State_Enabled

        QApplication.style().drawControl(QStyle.CE_PushButton, button, painter)
Ejemplo n.º 20
0
 def closeEvent(self, event):
     if self.sub is not None:
         self.sub.unregister()
         del self.sub
     try:
         self.ssh_output_file.close()
         self.ssh_error_file.close()
         # send Ctrl+C to remote process
         self.ssh_input_file.write('%s\n' % chr(3))
         self.ssh_input_file.close()
     except:
         pass
     self.finished_signal.emit(self.topic)
     if self.parent() is None:
         QApplication.quit()
Ejemplo n.º 21
0
 def paste_from_clipboard(self):
     '''
     Copy the file or folder to new position...
     '''
     if QApplication.clipboard().mimeData().hasText(
     ) and self._current_path:
         text = QApplication.clipboard().mimeData().text()
         if self.current_path and text.startswith('grpc://'):
             basename = os.path.basename(text)
             dest_path = os.path.join(self._current_path, basename)
             try:
                 nm.nmd().file.copy(text, dest_path)
                 self.reload_current_path(clear_cache=True)
             except Exception:
                 import traceback
                 print(traceback.format_exc())
Ejemplo n.º 22
0
    def paint(self, painter, option, index):
        '''
        Use the QTextDokument to represent the HTML text.
        @see: U{http://www.pyside.org/docs/pyside/PySide/QtGui/QAbstractItemDelegate.html#PySide.QtGui.QAbstractItemDelegate}
        '''
        options = QStyleOptionViewItem(option)
        self.initStyleOption(options, index)

        style = QApplication.style() if options.widget is None else options.widget.style()

        doc = QTextDocument()
        doc.setHtml(self.toHTML(options.text))
        doc.setTextWidth(option.rect.width())

        options.text = ''
        style.drawControl(QStyle.CE_ItemViewItem, options, painter)

        ctx = QAbstractTextDocumentLayout.PaintContext()

        # Highlighting text if item is selected
        # if (optionV4.state and QStyle::State_Selected):
        #  ctx.palette.setColor(QPalette::Text, optionV4.palette.color(QPalette::Active, QPalette::HighlightedText));

        textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options, options.widget)
        painter.save()
        painter.translate(QPoint(textRect.topLeft().x(), textRect.topLeft().y() - 3))
        painter.setClipRect(textRect.translated(-textRect.topLeft()))
        doc.documentLayout().draw(painter, ctx)

        painter.restore()
Ejemplo n.º 23
0
    def paint(self, painter, option, index):
        '''
        Use the QTextDokument to represent the HTML text.
        @see: U{http://www.pyside.org/docs/pyside/PySide/QtGui/QAbstractItemDelegate.html#PySide.QtGui.QAbstractItemDelegate}
        '''
        options = QStyleOptionViewItem(option)
        self.initStyleOption(options, index)

        style = QApplication.style(
        ) if options.widget is None else options.widget.style()

        doc = QTextDocument()
        doc.setHtml(self.toHTML(options.text))
        # doc.setTextWidth(option.rect.width())

        options.text = ''
        style.drawControl(QStyle.CE_ItemViewItem, options, painter)

        ctx = QAbstractTextDocumentLayout.PaintContext()

        # Highlighting text if item is selected
        # if (optionV4.state and QStyle::State_Selected):
        #  ctx.palette.setColor(QPalette::Text, optionV4.palette.color(QPalette::Active, QPalette::HighlightedText));

        textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options,
                                        options.widget)
        painter.save()
        painter.translate(
            QPoint(textRect.topLeft().x(),
                   textRect.topLeft().y() - 3))
        painter.setClipRect(textRect.translated(-textRect.topLeft()))
        doc.documentLayout().draw(painter, ctx)

        painter.restore()
 def keyPressEvent(self, event):
     '''
     Defines some of shortcuts for navigation/management in launch
     list view or topics view.
     '''
     key_mod = QApplication.keyboardModifiers()
     if not self.xmlFileView.state() == QAbstractItemView.EditingState:
         # remove history file from list by pressing DEL
         if event == QKeySequence.Delete:
             selected = self._launchItemsFromIndexes(self.xmlFileView.selectionModel().selectedIndexes(), False)
             for item in selected:
                 nm.settings().launch_history_remove(item.path)
                 self.launchlist_model.reloadCurrentPath()
         elif not key_mod and event.key() == Qt.Key_F4 and self.editXmlButton.isEnabled():
             # open selected launch file in xml editor by F4
             self.on_edit_xml_clicked()
         elif event == QKeySequence.Find:
             # set focus to filter box for packages
             self.searchPackageLine.setFocus(Qt.ActiveWindowFocusReason)
         elif event == QKeySequence.Paste:
             # paste files from clipboard
             self.launchlist_model.paste_from_clipboard()
         elif event == QKeySequence.Copy:
             # copy the selected items as file paths into clipboard
             selected = self.xmlFileView.selectionModel().selectedIndexes()
             indexes = []
             for s in selected:
                 indexes.append(self.launchlist_proxyModel.mapToSource(s))
             self.launchlist_model.copy_to_clipboard(indexes)
     if self.searchPackageLine.hasFocus() and event.key() == Qt.Key_Escape:
         # cancel package filtering on pressing ESC
         self.launchlist_model.show_packages(False)
         self.searchPackageLine.setText('')
         self.xmlFileView.setFocus(Qt.ActiveWindowFocusReason)
     QDockWidget.keyReleaseEvent(self, event)
Ejemplo n.º 25
0
def run(gui,debug=False):
    """
    @param gui: The gui to render and execute
    """
    
    if debug:
        str_traverse = StringTraverse()
        gui.traverse(str_traverse)
        
    rospy.init_node("guiname")
    code_traverse = pyqtTraverse()
    
    app = QApplication(sys.argv)
    
    gui.traverse(code_traverse)
    sys.exit(app.exec_())
Ejemplo n.º 26
0
 def keyPressEvent(self, event):
     '''
     Defines some of shortcuts for navigation/management in launch
     list view or topics view.
     '''
     key_mod = QApplication.keyboardModifiers()
     if not self.xmlFileView.state() == QAbstractItemView.EditingState:
         # remove history file from list by pressing DEL
         if event == QKeySequence.Delete:
             selected = self._launchItemsFromIndexes(self.xmlFileView.selectionModel().selectedIndexes(), False)
             for item in selected:
                 nm.settings().launch_history_remove(item.path)
                 self.launchlist_model.reloadCurrentPath()
         elif not key_mod and event.key() == Qt.Key_F4 and self.editXmlButton.isEnabled():
             # open selected launch file in xml editor by F4
             self.on_edit_xml_clicked()
         elif event == QKeySequence.Find:
             # set focus to filter box for packages
             self.searchPackageLine.setFocus(Qt.ActiveWindowFocusReason)
         elif event == QKeySequence.Paste:
             # paste files from clipboard
             self.launchlist_model.paste_from_clipboard()
         elif event == QKeySequence.Copy:
             # copy the selected items as file paths into clipboard
             selected = self.xmlFileView.selectionModel().selectedIndexes()
             indexes = []
             for s in selected:
                 indexes.append(self.launchlist_proxyModel.mapToSource(s))
             self.launchlist_model.copy_to_clipboard(indexes)
     if self.searchPackageLine.hasFocus() and event.key() == Qt.Key_Escape:
         # cancel package filtering on pressing ESC
         self.launchlist_model.show_packages(False)
         self.searchPackageLine.setText('')
         self.xmlFileView.setFocus(Qt.ActiveWindowFocusReason)
     QDockWidget.keyReleaseEvent(self, event)
Ejemplo n.º 27
0
 def on_search_result(self, search_text, found, path, index):
     '''
     A slot to handle a found text. It goes to the position in the text and select
     the searched text. On new file it will be open.
     :param search_text: the searched text
     :type search_text: str
     :param found: the text was found or not
     :type found: bool
     :param path: the path of the file the text was found
     :type path: str
     :param index: the position in the text
     :type index: int
     '''
     if found:
         if self.tabWidget.currentWidget().filename != path:
             focus_widget = QApplication.focusWidget()
             self.on_load_request(path)
             focus_widget.setFocus()
         cursor = self.tabWidget.currentWidget().textCursor()
         cursor.setPosition(index, QTextCursor.MoveAnchor)
         cursor.movePosition(QTextCursor.NextCharacter,
                             QTextCursor.KeepAnchor, len(search_text))
         self.tabWidget.currentWidget().setTextCursor(cursor)
         cursor_y = self.tabWidget.currentWidget().cursorRect().top()
         vbar = self.tabWidget.currentWidget().verticalScrollBar()
         vbar.setValue(vbar.value() + cursor_y * 0.8)
Ejemplo n.º 28
0
def run(gui, debug=False):
    """
    @param gui: The gui to render and execute
    """

    if debug:
        str_traverse = StringTraverse()
        gui.traverse(str_traverse)

    rospy.init_node("guiname")
    code_traverse = pyqtTraverse()

    app = QApplication(sys.argv)

    gui.traverse(code_traverse)
    sys.exit(app.exec_())
Ejemplo n.º 29
0
    def update_spectrogram(self):
        if self.spectrogram is not None:
            self.axes.clear()

            self.axes.imshow(self.spectrogram,
                             aspect="auto",
                             origin="lower",
                             cmap="hot")
            self.axes.grid(None)

            self.axes.set_ylabel("Freq. [bin]")
            self.axes.set_xlabel("Time [frame]")

            self.fig.tight_layout()

            self.canvas.draw()

        QApplication.processEvents()
 def paste_from_clipboard(self):
     '''
     Copy the file or folder to new position...
     '''
     if QApplication.clipboard().mimeData().hasText() and self.currentPath:
         text = QApplication.clipboard().mimeData().text()
         if text.startswith('file://'):
             path = text.replace('file://', '')
             basename = os.path.basename(text)
             ok = True
             if os.path.exists(os.path.join(self.currentPath, basename)):
                 basename, ok = QInputDialog.getText(None, 'File exists', 'New name (or override):', QLineEdit.Normal, basename)
             if ok and basename:
                 if os.path.isdir(path):
                     shutil.copytree(path, os.path.join(self.currentPath, basename))
                 elif os.path.isfile(path):
                     shutil.copy2(path, os.path.join(self.currentPath, basename))
                 self.reloadCurrentPath()
Ejemplo n.º 31
0
 def paste_from_clipboard(self):
     '''
     Copy the file or folder to new position...
     '''
     if QApplication.clipboard().mimeData().hasText() and self.currentPath:
         text = QApplication.clipboard().mimeData().text()
         if text.startswith('file://'):
             path = text.replace('file://', '')
             basename = os.path.basename(text)
             ok = True
             if os.path.exists(os.path.join(self.currentPath, basename)):
                 basename, ok = QInputDialog.getText(None, 'File exists', 'New name (or override):', QLineEdit.Normal, basename)
             if ok and basename:
                 if os.path.isdir(path):
                     shutil.copytree(path, os.path.join(self.currentPath, basename))
                 elif os.path.isfile(path):
                     shutil.copy2(path, os.path.join(self.currentPath, basename))
                 self.reloadCurrentPath()
Ejemplo n.º 32
0
    def expand_item(self, path, path_id, clear_cache=False):
        '''
        Returns for the given item and path the file path if this is a file. Otherwise the
        folder will be expanded and None will be returned.

        :param str path: the real path of the item
        :param int path_id: the id of the path
        :param bool clear_cache: clear cache before reload
        :return: path of the launch file or None
        :rtype: str
        :raise Exception: if no path to given item was found
        '''
        if path_id in [PathItem.NOTHING]:
            return None
        has_shift_mod = Qt.ShiftModifier & QApplication.keyboardModifiers()
        if path_id in [
                PathItem.LAUNCH_FILE, PathItem.CFG_FILE, PathItem.PROFILE,
                PathItem.FILE, PathItem.RECENT_FILE, PathItem.LAUNCH_FILE
        ]:
            if not has_shift_mod:
                return path
        root = self.invisibleRootItem()
        while root.rowCount():
            root.removeRow(0)
        self.pyqt_workaround.clear()
        if has_shift_mod:
            if path_id in [
                    PathItem.LAUNCH_FILE, PathItem.CFG_FILE, PathItem.PROFILE,
                    PathItem.FILE, PathItem.RECENT_FILE, PathItem.LAUNCH_FILE
            ]:
                self._current_path = os.path.dirname(path)
            else:
                self._current_path = nmdurl.nmduri()
        else:
            if path_id in [PathItem.ROOT]:
                surl, spath = nmdurl.split(path, with_scheme=True)
                if self._is_root(path) or spath in ['', os.path.sep]:
                    self._current_path = nmdurl.nmduri()
                elif self._is_ros_root(path):
                    self._current_path = surl
                else:
                    dir_path = os.path.dirname(spath)
                    self._current_path = nmdurl.join(surl, dir_path)
            elif self._current_path != path:
                self._current_path = path
        self._add_path(self._current_path, PathItem.ROOT, 0, 0, 'loading...')
        nm.nmd().file.list_path_threaded(self._current_path, clear_cache)
        # TODO: add functionality to go deep automatically
        #         else:
        #             key_mod = QApplication.keyboardModifiers()
        #             onestep = False
        #             if key_mod & Qt.ControlModifier:
        #                 onestep = True
        #             root_path, items = self._moveDown(path, onestep)
        #        self._setNewList((root_path, items))
        return None
Ejemplo n.º 33
0
 def create_application(self, argv):
     from python_qt_binding.QtCore import Qt
     from python_qt_binding.QtGui import QApplication
     QApplication.setAttribute(Qt.AA_X11InitThreads, True)
     app = QApplication(argv)
     app.setAttribute(Qt.AA_DontShowIconsInMenus, False)
     return app
Ejemplo n.º 34
0
def main(name, anonymous=False):
  masteruri = init_cfg_path()

  args = rospy.myargv(argv=sys.argv)
  # decide to show main or echo dialog
  if len(args) >= 4 and args[1] == '-t':
    name = ''.join([name, '_echo'])
    anonymous = True

  try:
    from python_qt_binding.QtGui import QApplication
  except:
    print >> sys.stderr, "please install 'python-pyside' package!!"
    sys.exit(-1)
  rospy.init_node(name, anonymous=anonymous, log_level=rospy.DEBUG)
  setTerminalName(rospy.get_name())
  setProcessName(rospy.get_name())

  # Initialize Qt
  global app
  app = QApplication(sys.argv)

  # decide to show main or echo dialog
  import main_window, echo_dialog
  global main_form
  if len(args) >= 4 and args[1] == '-t':
    show_hz_only = (len(args) > 4 and args[4] == '--hz')
    main_form = echo_dialog.EchoDialog(args[2], args[3], show_hz_only, masteruri)
  else:
    local_master = init_globals(masteruri)

    #start the gui
    main_form = main_window.MainWindow(args, not local_master)

  if not rospy.is_shutdown():
    os.chdir(PACKAGE_DIR) # change path to be able to the images of descriptions
    main_form.show()
    exit_code = -1
    rospy.on_shutdown(finish)
    exit_code = app.exec_()
Ejemplo n.º 35
0
 def paste_from_clipboard(self):
     '''
     Copy the file or folder to new position...
     '''
     if QApplication.clipboard().mimeData().hasText(
     ) and self._current_path:
         text = QApplication.clipboard().mimeData().text()
         if self.current_path and text.startswith('grpc://'):
             basename = os.path.basename(text)
             dest_path = os.path.join(self._current_path, basename)
             try:
                 if text == dest_path:
                     dest_path = self._autorename(dest_path)
                     rospy.logdebug("Autorename destination from %s to %s" %
                                    (text, dest_path))
                 rospy.logdebug("Copy %s to %s" % (text, dest_path))
                 nm.nmd().file.copy(text, dest_path)
                 self.reload_current_path(clear_cache=True)
             except Exception as err:
                 MessageBox.warning(None, "Copy failed",
                                    "Copy failed: %s" % utf8(err))
                 import traceback
                 print(traceback.format_exc())
Ejemplo n.º 36
0
 def _copy_text_to_clipboard(self):
     # Get tab indented text for all selected items
     def get_distance(item, ancestor, distance=0):
         parent = item.parent()
         if parent == None:
             return distance
         else:
             return get_distance(parent, ancestor, distance + 1)
     text = ''
     for i in self.get_all_items():
         if i in self.selectedItems():
             text += ('\t' * (get_distance(i, None))) + i.text(0) + '\n'
     # Copy the text to the clipboard
     clipboard = QApplication.clipboard()
     clipboard.setText(text)
Ejemplo n.º 37
0
 def _copy_text_to_clipboard(self):
     # Get tab indented text for all selected items
     def get_distance(item, ancestor, distance=0):
         parent = item.parent()
         if parent == None:
             return distance
         else:
             return get_distance(parent, ancestor, distance + 1)
     text = ''
     for i in self.get_all_items():
         if i in self.selectedItems():
             text += ('\t' * (get_distance(i, None))) + i.text(0) + '\n'
     # Copy the text to the clipboard
     clipboard = QApplication.clipboard()
     clipboard.setText(text)
Ejemplo n.º 38
0
class RQTWrapper(object):
    def __init__(self, rqt_plugin_name):
        signal.signal(signal.SIGINT, self._shutdown)
        self._app = QApplication(sys.argv)
        self._rqt_wrapper = Switcher(rqt_plugin_name)
        # Let the interpreter run each 200 ms, this gives a chance for CTRL-C signals to come through
        self._give_signals_a_chance_timer = QTimer()
        self._give_signals_a_chance_timer.timeout.connect(lambda: None)
        self._give_signals_a_chance_timer.start(200)

    def exec_(self):
        return self._app.exec_()

    def _shutdown(self, signum, f):
        if signum == signal.SIGINT:
            self._rqt_wrapper.shutdown()
Ejemplo n.º 39
0
 def on_search_result_on_open(self, search_text, found, path, index):
     '''
     Like on_search_result, but skips the text in comments.
     '''
     if found:
         if self.tabWidget.currentWidget().filename != path:
             focus_widget = QApplication.focusWidget()
             self.on_load_request(path)
             focus_widget.setFocus()
         comment_start = self.tabWidget.currentWidget().document().find('<!--', index, QTextDocument.FindBackward)
         if not comment_start.isNull():
             comment_end = self.tabWidget.currentWidget().document().find('-->', comment_start)
             if not comment_end.isNull() and comment_end.position() > index + len(search_text):
                 # commented -> retrun
                 return
     self.on_search_result(search_text, found, path, index)
Ejemplo n.º 40
0
 def on_search_result_on_open(self, search_text, found, path, index):
     '''
     Like on_search_result, but skips the text in comments.
     '''
     if found:
         if self.tabWidget.currentWidget().filename != path:
             focus_widget = QApplication.focusWidget()
             self.on_load_request(path)
             focus_widget.setFocus()
         comment_start = self.tabWidget.currentWidget().document().find('<!--', index, QTextDocument.FindBackward)
         if not comment_start.isNull():
             comment_end = self.tabWidget.currentWidget().document().find('-->', comment_start)
             if not comment_end.isNull() and comment_end.position() > index + len(search_text):
                 # commented -> retrun
                 return
     self.on_search_result(search_text, found, path, index)
Ejemplo n.º 41
0
 def on_load_as_default(self):
     '''
     Tries to load the selected launch file as default configuration. The button
     is only enabled and this method is called, if the button was enabled by
     on_launch_selection_clicked()
     '''
     key_mod = QApplication.keyboardModifiers()
     if (key_mod & Qt.ShiftModifier):
         self.loadXmlAsDefaultButton.showMenu()
     else:
         selected = self._launchItemsFromIndexes(self.xmlFileView.selectionModel().selectedIndexes(), False)
         for item in selected:
             path = self.launchlist_model.expandItem(item.name, item.path, item.id)
             if path is not None:
                 rospy.loginfo("LOAD the launch file as default: %s", path)
                 self.launchlist_model.add2LoadHistory(path)
                 self.load_as_default_signal.emit(path, None)
Ejemplo n.º 42
0
 def on_search_result_on_open(self, search_text, found, path, startpos, endpos, linenr, line_text):
     '''
     Like on_search_result, but skips the text in comments.
     '''
     if found:
         self._search_node_count += 1
         if self._search_node_count > 1:
             self.on_toggled_find(True, only_results=True)
         self.find_dialog.current_search_text = search_text
         self.find_dialog.on_search_result(search_text, found, path, startpos, endpos, linenr, line_text)
         self.on_graph_info("search thread: found %s in '%s:%d'" % (search_text, path, linenr))
         if self.tabWidget.currentWidget().filename != path:
             focus_widget = QApplication.focusWidget()
             self.on_load_request(path)
             if focus_widget is not None:
                 focus_widget.setFocus()
         self.tabWidget.currentWidget().select(startpos, endpos, True)
Ejemplo n.º 43
0
 def on_search_result(self, search_text, found, path, startpos, endpos, linenr=-1, line_text=''):
     '''
     A slot to handle a found text. It goes to the position in the text and select
     the searched text. On new file it will be open.
     :param search_text: the searched text
     :type search_text: str
     :param found: the text was found or not
     :type found: bool
     :param path: the path of the file the text was found
     :type path: str
     :param startpos: the position in the text
     :type startpos: int
     :param endpos: the end position in the text
     :type endpos: int
     '''
     if found:
         if self.tabWidget.currentWidget().filename != path:
             focus_widget = QApplication.focusWidget()
             self.on_load_request(path)
             focus_widget.setFocus()
         self.tabWidget.currentWidget().select(startpos, endpos, False)
Ejemplo n.º 44
0
 def on_search_result(self, search_text, found, path, index):
     '''
     A slot to handle a found text. It goes to the position in the text and select
     the searched text. On new file it will be open.
     :param search_text: the searched text
     :type search_text: str
     :param found: the text was found or not
     :type found: bool
     :param path: the path of the file the text was found
     :type path: str
     :param index: the position in the text
     :type index: int
     '''
     if found:
         if self.tabWidget.currentWidget().filename != path:
             focus_widget = QApplication.focusWidget()
             self.on_load_request(path)
             focus_widget.setFocus()
         cursor = self.tabWidget.currentWidget().textCursor()
         cursor.setPosition(index, QTextCursor.MoveAnchor)
         cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor, len(search_text))
         self.tabWidget.currentWidget().setTextCursor(cursor)
Ejemplo n.º 45
0
            message_class = roslib.message.get_message_class(topic_type)
            if message_class is None:
                qWarning(
                    'TopicCompleter.update_topics(): '
                    'could not get message class for topic type "%s" on topic "%s"'
                    % (topic_type, topic_path))
                continue
            message_instance = message_class()
            self.model().add_message(message_instance, topic_name, topic_type,
                                     topic_path)


if __name__ == '__main__':
    import sys
    from python_qt_binding.QtGui import QApplication, QComboBox, QLineEdit, QMainWindow, QTreeView, QVBoxLayout, QWidget
    app = QApplication(sys.argv)
    mw = QMainWindow()
    widget = QWidget(mw)
    layout = QVBoxLayout(widget)

    edit = QLineEdit()
    edit_completer = TopicCompleter(edit)
    # edit_completer.setCompletionMode(QCompleter.InlineCompletion)
    edit.setCompleter(edit_completer)

    combo = QComboBox()
    combo.setEditable(True)
    combo_completer = TopicCompleter(combo)
    # combo_completer.setCompletionMode(QCompleter.InlineCompletion)
    combo.lineEdit().setCompleter(combo_completer)
Ejemplo n.º 46
0
    def _event(self, e):
        if e.type() == QEvent.MouseButtonPress and e.button() == Qt.LeftButton:
            qDebug('%spress, rel=%s, global=%s, diff=%s' % ((' - pseudo ' if self._releasing_and_repressing_while_dragging else ''), e.pos(), e.globalPos(), e.globalPos() - self.pos()))
        if e.type() == QEvent.MouseButtonRelease and e.button() == Qt.LeftButton:
            qDebug('%srelease, rel=%s, global=%s, diff=%s' % ((' - pseudo ' if self._releasing_and_repressing_while_dragging else ''), e.pos(), e.globalPos(), e.globalPos() - self.pos()))

        # store local position when pressing button before starting the custom drag'n'drop
        # only allow when layout is not frozen
        if self._dragging_parent is None and e.type() == QEvent.MouseButtonPress and e.button() == Qt.LeftButton and bool(self.features() & QDockWidget.DockWidgetMovable):
            self._dragging_local_pos = e.pos()

        if self._dragging_parent is None and self._dragging_local_pos is not None and e.type() == QEvent.Move and QApplication.mouseButtons() & Qt.LeftButton:
            if self._widget_at(e.pos()) is not None:
                qDebug('DockWidget._event() start drag, dockwidget=%s, parent=%s, floating=%s, pos=%s' % (str(self), str(self.parent()), str(self.isFloating()), str(self._dragging_local_pos)))
                self._dragging_parent = self.parent()
                # ignore further mouse events so that the widget behind this dock widget can be determined
                self.setAttribute(Qt.WA_TransparentForMouseEvents)

                # collect all main windows (except self.main_window) to re-implement QApplication.widgetAt() in self._widget_at()
                self._main_windows = [self._container_manager.get_root_main_window()]
                for container in self._container_manager.get_containers():
                    if container == self:
                        continue
                    self._main_windows.append(container.main_window)

        # unset local position when releasing button even when custom drag'n'drop has not been started
        if self._dragging_local_pos is not None and e.type() == QEvent.MouseButtonRelease and e.button() == Qt.LeftButton and not self._releasing_and_repressing_while_dragging:
            self._dragging_local_pos = None

        if self._dragging_parent is not None and e.type() == QEvent.MouseButtonRelease and e.button() == Qt.LeftButton and not self._releasing_and_repressing_while_dragging:
            qDebug('DockWidget._event() stop drag, dockwidget=%s, parent=%s\n' % (self, self.parent()))
            self._dragging_parent = None
            self.setAttribute(Qt.WA_TransparentForMouseEvents, False)
            self._main_windows = []

        if self._dragging_parent is not None and e.type() == QEvent.MouseMove and e.buttons() & Qt.LeftButton and not self._releasing_and_repressing_while_dragging:
            widget = self._widget_at(e.globalPos())
            new_parent = self._get_new_parent(widget)
            #print 'new_parent', new_parent, (new_parent.objectName() if new_parent else '')
            if new_parent is not None and new_parent != self.parent():
                self._releasing_and_repressing_while_dragging = True

                # schedule stop of pseudo drag'n'drop and let it complete
                mouse_release_event = QMouseEvent(QEvent.MouseButtonRelease, self._dragging_local_pos, e.globalPos(), Qt.LeftButton, Qt.NoButton, e.modifiers())
                QApplication.instance().postEvent(self, mouse_release_event)
                QApplication.sendPostedEvents()

                # schedule reparent to hovered main window and let it complete
                reparent_event = ReparentEvent(self, new_parent)
                QApplication.instance().postEvent(self._container_manager, reparent_event)
                QApplication.sendPostedEvents()

                # reenable mouse events to be able to receive upcoming pseudo mouse events
                self.setAttribute(Qt.WA_TransparentForMouseEvents, False)

                # schedule restart of pseudo drag'n'drop and let it complete
                mouse_repress_event = QMouseEvent(QEvent.MouseButtonPress, self._dragging_local_pos, e.globalPos(), Qt.LeftButton, Qt.LeftButton, e.modifiers())
                QApplication.instance().postEvent(self, mouse_repress_event)
                QApplication.sendPostedEvents()

                # schedule move to trigger dock widget drag'n'drop required for snapping and showing rubber band and let it complete
                # move forth...
                mouse_move_event = QMouseEvent(QEvent.MouseMove, self._dragging_local_pos, e.globalPos() + QPoint(QApplication.startDragDistance(), 1), Qt.NoButton, Qt.LeftButton, e.modifiers())
                QApplication.instance().postEvent(self, mouse_move_event)
                QApplication.sendPostedEvents()
                # ...and back
                mouse_move_event = QMouseEvent(QEvent.MouseMove, self._dragging_local_pos, e.globalPos(), Qt.NoButton, Qt.LeftButton, e.modifiers())
                QApplication.instance().postEvent(self, mouse_move_event)
                QApplication.sendPostedEvents()

                # restore attributes after repressing the button
                self.setAttribute(Qt.WA_TransparentForMouseEvents)

                self._releasing_and_repressing_while_dragging = False

        return super(DockWidget, self).event(e)
    def __init__(self, qTextPanel):
        self.textPanel = qTextPanel;
    
    def setText(self, theStr):
        self.textPanel.clear();
        self.textPanel.setText(theStr);
    
    def getText(self):
        # Get text field text as plain text, and convert
        # unicode to ascii, ignoring errors:
        #return self.toPlainText().encode('ascii', 'ignore');
        return self.textPanel.toPlainText().encode('utf-8');
    
    def textCursor(self):
        return self.textPanel.textCursor();

    def getCursorPos(self):
        return self.textCursor().position;

    def isEmpty(self):
        return len(self.textPanel.toPlainText()) == 0;
          
if __name__ == '__main__':
    
    app = QApplication(sys.argv);
    ui = MarkupManagementUI();
    ui.show();
    app.exec_();
    sys.exit();
        
        
Ejemplo n.º 48
0
    def _rightclick_menu(self, event):
        """
        Dynamically builds the rightclick menu based on the unique column data
        from the passed in datamodel and then launches it modally
        :param event: the mouse event object, ''QMouseEvent''
        """
        severities = {}
        for severity, label in Message.SEVERITY_LABELS.items():
            if severity in self._model.get_unique_severities():
                severities[severity] = label
        nodes = sorted(self._model.get_unique_nodes())
        topics = sorted(self._model.get_unique_topics())

        # menutext entries turned into
        menutext = []
        menutext.append([
            self.tr('Exclude'),
            [[self.tr('Severity'), severities], [self.tr('Node'), nodes],
             [self.tr('Topic'), topics], [self.tr('Selected Message(s)')]]
        ])
        menutext.append([
            self.tr('Highlight'),
            [[self.tr('Severity'), severities], [self.tr('Node'), nodes],
             [self.tr('Topic'), topics], [self.tr('Selected Message(s)')]]
        ])
        menutext.append([self.tr('Copy Selected')])
        menutext.append([self.tr('Browse Selected')])

        menu = QMenu()
        submenus = []
        subsubmenus = []
        for item in menutext:
            if len(item) > 1:
                submenus.append(QMenu(item[0], menu))
                for subitem in item[1]:
                    if len(subitem) > 1:
                        subsubmenus.append(QMenu(subitem[0], submenus[-1]))
                        if isinstance(subitem[1], dict):
                            for key in sorted(subitem[1].keys()):
                                action = subsubmenus[-1].addAction(
                                    subitem[1][key])
                                action.setData(key)
                        else:
                            for subsubitem in subitem[1]:
                                subsubmenus[-1].addAction(subsubitem)
                        submenus[-1].addMenu(subsubmenus[-1])
                    else:
                        submenus[-1].addAction(subitem[0])
                menu.addMenu(submenus[-1])
            else:
                menu.addAction(item[0])
        action = menu.exec_(event.globalPos())

        if action is None or action == 0:
            return
        elif action.text() == self.tr('Browse Selected'):
            self._show_browsers()
        elif action.text() == self.tr('Copy Selected'):
            rowlist = []
            for current in self.table_view.selectionModel().selectedIndexes():
                rowlist.append(self._proxy_model.mapToSource(current).row())
            copytext = self._model.get_selected_text(rowlist)
            if copytext is not None:
                clipboard = QApplication.clipboard()
                clipboard.setText(copytext)
        elif action.text() == self.tr('Selected Message(s)'):
            if action.parentWidget().title() == self.tr('Highlight'):
                self._process_highlight_exclude_filter(action.text(),
                                                       'Message', False)
            elif action.parentWidget().title() == self.tr('Exclude'):
                self._process_highlight_exclude_filter(action.text(),
                                                       'Message', True)
            else:
                raise RuntimeError(
                    "Menu format corruption in ConsoleWidget._rightclick_menu()"
                )
        else:
            # This processes the dynamic list entries (severity, node and topic)
            try:
                roottitle = action.parentWidget().parentWidget().title()
            except:
                raise RuntimeError(
                    "Menu format corruption in ConsoleWidget._rightclick_menu()"
                )

            if roottitle == self.tr('Highlight'):
                self._process_highlight_exclude_filter(
                    action.text(),
                    action.parentWidget().title(), False)
            elif roottitle == self.tr('Exclude'):
                self._process_highlight_exclude_filter(
                    action.text(),
                    action.parentWidget().title(), True)
            else:
                raise RuntimeError(
                    "Unknown Root Action %s selected in ConsoleWidget._rightclick_menu()"
                    % roottitle)
Ejemplo n.º 49
0
                    (zoom_factor * self._canvas_display_height)))
            self.rescale_axis_x(self._last_canvas_x - canvas_x)
        self._last_canvas_x = canvas_x
        self._last_canvas_y = canvas_y

    def wheelEvent(self, event):  # mouse wheel zooms the y-axis
        canvas_y = event.y() - self.canvas().y()
        zoom_factor = max(-0.6, min(0.6, (event.delta() / 120) / 6.0))
        delta_y = (self.canvas().height() / 2.0) - canvas_y
        self.move_canvas(0, zoom_factor * delta_y * 1.0225)
        self.scale_axis_y(
            max(
                0.0005, self._canvas_display_height -
                zoom_factor * self._canvas_display_height))


if __name__ == '__main__':
    from python_qt_binding.QtGui import QApplication

    app = QApplication(sys.argv)
    plot = QwtDataPlot()
    plot.resize(700, 500)
    plot.show()
    plot.add_curve(0, '(x/500)^2')
    plot.add_curve(1, 'sin(x / 20) * 500')
    for i in range(plot._num_value_saved):
        plot.update_value(0, (i / 500.0) * (i / 5.0))
        plot.update_value(1, math.sin(i / 20.0) * 500)

    sys.exit(app.exec_())
Ejemplo n.º 50
0
                              index_parent_sel,
                                  #index_parent_sel.data(Qt.DisplayRole),
                              index_internalid))
        elif len(deselected.indexes()) > 0:
            print(tabular_format.format(
                              del_or_sel,
                              index_deselected,
                              index_deselected.row(),
                              index_deselected.data(Qt.DisplayRole).toString(),
                              #curr_qstd_item,
                              #    curr_qstd_item.data(),
                                  index_parent_desel,
                              #  index_parent_desel.data(Qt.DisplayRole),
                                  index_internalid))
            self.selectionModel.select(index_deselected,
                                       QItemSelectionModel.Deselect)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    #window = TreeviewWidgetSelectProve()
    #window = PrvTreeviewNest()
    window = TreeviewWidgetSelectProve()
    window.resize(320, 240)
    # window.show();
    window.setWindowTitle(
         QApplication.translate("toplevel", "Top-level widget"))
    # window.add_cols()

    sys.exit(app.exec_())
            self.stopped = True
            self.textToSpeechPlayer.stop()


if __name__ == "__main__":

    # Create socket pair to communicate between the
    # Unix signal handler and the Qt event loop:
    rsock, wsock = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)

    # Handler for SIGUSR1 and SIGUSR2
    def sigusr1_2_handler(signum, stack):
        print "Received Signal:", signum
        wsock.send(str(signum) + "\n")

    app = QApplication(sys.argv)

    # To find the sounds, we need the absolute directory
    # path to this script:
    scriptDir = os.path.dirname(os.path.abspath(sys.argv[0]))
    # speakeasyController = SpeakEasyController(scriptDir, stand_alone=False);
    # speakeasyController = SpeakEasyController(scriptDir, stand_alone=True);

    if len(sys.argv) > 1:
        if sys.argv[1] == "local":
            print "Starting SpeakEasy in local (i.e. non-ROS) mode."
            speakeasyController = SpeakEasyController(scriptDir, unix_sig_notify_read_socket=rsock, stand_alone=True)
        else:
            try:
                rospy.loginfo(
                    "Will attempt to start SpeakEasy in ROS mode. If fail, switch to local mode. Possibly a few seconds delay..."
 def actionPaste(self):
     # Also called by handleOS_SIGUSR1_2
     textArea = self.gui.speechInputFld
     currCursor = textArea.textCursor()
     currCursor.insertText(QApplication.clipboard().text())
Ejemplo n.º 53
0
 def __init__(self, img):
     splash_pix = QPixmap(img)
     self.splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
     self.splash.setMask(splash_pix.mask())
     self.splash.show()
     QApplication.processEvents()
    def _rightclick_menu(self, event):
        """
        Dynamically builds the rightclick menu based on the unique column data
        from the passed in datamodel and then launches it modally
        :param event: the mouse event object, ''QMouseEvent''
        """
        severities = {}
        for severity, label in Message.SEVERITY_LABELS.items():
            if severity in self._model.get_unique_severities():
                severities[severity] = label
        nodes = sorted(self._model.get_unique_nodes())
        topics = sorted(self._model.get_unique_topics())

        # menutext entries turned into
        menutext = []
        menutext.append([self.tr('Exclude'), [[self.tr('Severity'), severities], [self.tr('Node'), nodes], [self.tr('Topic'), topics], [self.tr('Selected Message(s)')]]])
        menutext.append([self.tr('Highlight'), [[self.tr('Severity'), severities], [self.tr('Node'), nodes], [self.tr('Topic'), topics], [self.tr('Selected Message(s)')]]])
        menutext.append([self.tr('Copy Selected')])
        menutext.append([self.tr('Browse Selected')])

        menu = QMenu()
        submenus = []
        subsubmenus = []
        for item in menutext:
            if len(item) > 1:
                submenus.append(QMenu(item[0], menu))
                for subitem in item[1]:
                    if len(subitem) > 1:
                        subsubmenus.append(QMenu(subitem[0], submenus[-1]))
                        if isinstance(subitem[1], dict):
                            for key in sorted(subitem[1].keys()):
                                action = subsubmenus[-1].addAction(subitem[1][key])
                                action.setData(key)
                        else:
                            for subsubitem in subitem[1]:
                                subsubmenus[-1].addAction(subsubitem)
                        submenus[-1].addMenu(subsubmenus[-1])
                    else:
                        submenus[-1].addAction(subitem[0])
                menu.addMenu(submenus[-1])
            else:
                menu.addAction(item[0])
        action = menu.exec_(event.globalPos())

        if action is None or action == 0:
            return
        elif action.text() == self.tr('Browse Selected'):
            self._show_browsers()
        elif action.text() == self.tr('Copy Selected'):
            rowlist = []
            for current in self.table_view.selectionModel().selectedIndexes():
                rowlist.append(self._proxy_model.mapToSource(current).row())
            copytext = self._model.get_selected_text(rowlist)
            if copytext is not None:
                clipboard = QApplication.clipboard()
                clipboard.setText(copytext)
        elif action.text() == self.tr('Selected Message(s)'):
            if action.parentWidget().title() == self.tr('Highlight'):
                self._process_highlight_exclude_filter(action.text(), 'Message', False)
            elif action.parentWidget().title() == self.tr('Exclude'):
                self._process_highlight_exclude_filter(action.text(), 'Message', True)
            else:
                raise RuntimeError("Menu format corruption in ConsoleWidget._rightclick_menu()")
        else:
            # This processes the dynamic list entries (severity, node and topic)
            try:
                roottitle = action.parentWidget().parentWidget().title()
            except:
                raise RuntimeError("Menu format corruption in ConsoleWidget._rightclick_menu()")

            if roottitle == self.tr('Highlight'):
                self._process_highlight_exclude_filter(action.text(), action.parentWidget().title(), False)
            elif roottitle == self.tr('Exclude'):
                self._process_highlight_exclude_filter(action.text(), action.parentWidget().title(), True)
            else:
                raise RuntimeError("Unknown Root Action %s selected in ConsoleWidget._rightclick_menu()" % roottitle)
        self.testButton.clicked.disconnect(self.oneButtonAvailable);        
        self.testButton.clicked.connect(self.noSetAvailable);
        
    def noSetAvailable(self):
        testButtonSetArray = [];
        buttonSetChoiceDialog = ButtonSetPopupSelector(iter(testButtonSetArray));
        #buttonSetChoiceDialog.show();
        choiceResult = buttonSetChoiceDialog.exec_();
        print "Choice result: " + str(choiceResult);
        buttonSetChoiceDialog.deleteLater();
        
        # Rewire the test button for the next text:
        self.testButton.setText("Exit");
        self.testButton.clicked.disconnect(self.noSetAvailable);        
        self.testButton.clicked.connect(self.close);
        
    def exitApp(self):
        self.close();
    
if __name__ == "__main__":
    
    style = QStyleFactory.create("Cleanlooks");
    QApplication.setStyle(style);
    app = QApplication(sys.argv);

    theTester = Tester();
    
        
    # Enter Qt application main loop
    sys.exit(app.exec_());    
Ejemplo n.º 56
0
 def _translate(self, text):
     if hasattr(QApplication, "UnicodeUTF8"):
         return QApplication.translate("Editor", text, None, QApplication.UnicodeUTF8)
     else:
         return QApplication.translate("Editor", text, None)
Ejemplo n.º 57
0
 def _translate(self, text):
     if hasattr(QApplication, "UnicodeUTF8"):
         return QApplication.translate("Form", text, None, QApplication.UnicodeUTF8)
     else:
         return QApplication.translate("Form", text, None)
#!/usr/bin/env python

import sys
from python_qt_binding.QtCore import QSettings, Qt
from python_qt_binding.QtGui import QAction, QApplication, QDockWidget, QToolBar, QMainWindow

app = QApplication(sys.argv)

settings = QSettings(QSettings.IniFormat, QSettings.UserScope, 'test', 'test')

mw = QMainWindow()
mw.resize(800, 600)
mw.show()

tb = QToolBar()
tb.setObjectName('toolbar')
mw.addToolBar(tb)

count_dock_widgets = 0

def add_dock_widget(orientation):
    global count_dock_widgets
    count_dock_widgets += 1
    dw = QDockWidget('dockwidget%d' % count_dock_widgets, mw)
    dw.setObjectName('dockwidget%d' % count_dock_widgets)
    mw.addDockWidget(Qt.BottomDockWidgetArea, dw, orientation)

def add_horizontal(self):
    add_dock_widget(Qt.Horizontal)

def add_vertical(self):
Ejemplo n.º 59
0
    def _widget_at(self, global_point):
        #print '_widget_at()', global_point#, local_point
        widget = QApplication.widgetAt(global_point)
        #print '- widget', widget, (widget.objectName() if widget is not None else '')
        root_main_window = self._container_manager.get_root_main_window()

        # work around bug where root main window is detected when point is near but not inside it
        if widget == root_main_window and not self._widget_contains(root_main_window, global_point):
            #print '- work around to large root main window'
            widget = None

        # work around bug where dock widget is floating and no widget is found
        if widget is None and self.isFloating():
            # determine all main windows which match the point
            overlapping = {}
            for main_window in self._main_windows:
                if self._widget_contains(main_window, global_point):
                    parent = main_window.parent()
                    is_floating = parent is None or parent.isFloating()
                    overlapping[main_window] = is_floating
            #print 'overlapping', overlapping

            if len(overlapping) == 1:
                # only found one candidate so pick it
                widget, _ = overlapping.popitem()
            elif len(overlapping) > 1:
                # try to determine which main window is the right one
                # determined docked main windows
                overlapping_docked = [mw for mw, floating in overlapping.iteritems() if not floating]
                #print 'overlapping_docked', overlapping_docked

                # if at max one of the main windows is floating
                if len(overlapping_docked) >= len(overlapping) - 1:
                    # the floating main window is not considered because the docked ones are children of it

                    # consider all docked main windows and remove parent if both parent and child are in the list
                    #print 'considered docked main windows', overlapping_docked
                    parents = []
                    for mw1 in overlapping_docked:
                        # parent of the main window is a dock widget container
                        parent = mw1.parent()
                        if parent is None:
                            continue
                        # parent of the dock widget container is a main window
                        parent = parent.parent()
                        if parent is None:
                            continue
                        for mw2 in overlapping_docked:
                            if mw2 == parent:
                                parents.append(mw2)
                    for parent in parents:
                        overlapping_docked.remove(parent)
                    #print 'considered non-parent main windows', overlapping_docked

                    # if only one docked main window is found then pick it
                    if len(overlapping_docked) == 1:
                        #print '- pick single remaining main window'
                        widget = overlapping_docked[0]
                    else:
                        #print '- found multiple main windows - could not determine which one is on top'
                        pass
                # TODO any more heuristic possible?
                # if all remaining docked main windows have a most common ancestor use the order of children() to determine topmost
        return widget