Example #1
0
 def __init__(self, gui):
     super(JoystickButton, self).__init__()
     self.gui = gui  # parent widget
     self.size = 360  # size in pixels of the push button
     self.state = None  # a QPoint representing the position of the crosshair in pixels
     self.pan_limits = (0, 360)  # width of the push button in pixels
     self.tilt_limits = (0, 360)  # height of the push button in pixels
     self.setCheckable(True)  # allow the push button to be 'checked'
     self.setFixedWidth(self.size)
     self.setFixedHeight(self.size)
     self.center = QPoint(
         self.size / 2.0, self.size / 2.0
     )  # (0,0) in pixels start from the upper left corner of the push button, so set the center to the middle (QPoint type)
     self.current_pos = QPoint(
         self.size / 2.0, self.size / 2.0
     )  # a QPoint representing the current position of the turret in pixels
     self.pan_deg_limits = [
         self.gui.name_map["pan"]["min_lower_limit"],
         self.gui.name_map["pan"]["max_upper_limit"]
     ]  # Pan joint limits in degrees
     self.tilt_deg_limits = [
         self.gui.name_map["tilt"]["min_lower_limit"],
         self.gui.name_map["tilt"]["max_upper_limit"]
     ]  # Tilt joint limits in degrees
     self.setJointCommands([
         float(self.gui.name_map["pan"]["display"].text()),
         float(self.gui.name_map["tilt"]["display"].text())
     ])  # set the default crosshair position to the current turret position
Example #2
0
def transformPointToPixelCoordinates(pt, map, image_size):
    map_point_f = ((pt - QPointF(map.map.info.origin.position.x,
                                 map.map.info.origin.position.y)) *
                   (1.0 / map.map.info.resolution))
    map_point = QPoint(int(map_point_f.x()), int(map_point_f.y()))
    map_size = QSize(map.map.info.width, map.map.info.height)
    scaled_point = scalePoint(map_point, map_size, image_size)
    return QPoint(scaled_point.x(), image_size.height() - scaled_point.y() - 1)
Example #3
0
    def __init__(self, parent=None):
        QTabBar.__init__(self, parent)

        self.setAcceptDrops(True)
        self.setElideMode(Qt.ElideRight)
        self.setSelectionBehaviorOnRemove(QTabBar.SelectLeftTab)

        self.drag_start_pos = QPoint()
        self.drag_droped_pos = QPoint()
        self.mouse_cursor = QCursor()
        self.drag_initiated = False
Example #4
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 paintEvent(self, event):
        geom = super(AxisWidget, self).geometry()
        h = geom.height()
        w = geom.width()

        box = QRect(2, 2, w - 4, h - 4)
        horiz = QLine(2, h / 2, w - 2, h / 2)
        vert = QLine(w / 2, 2, w / 2, h - 2)
        targ = QPoint(self._x * (w - 4) / 2 + w / 2,
                      self._y * (h - 4) / 2 + h / 2)

        plt = super(AxisWidget, self).palette()
        linebrsh = plt.dark()
        targetbrsh = plt.highlight()

        linepen = QPen(linebrsh, 1, Qt.SolidLine, Qt.SquareCap)
        targetpen = QPen(targetbrsh, 2, Qt.SolidLine, Qt.SquareCap)

        qp = QPainter()
        qp.begin(self)
        qp.setPen(linepen)
        qp.drawRect(box)
        qp.drawLine(horiz)
        qp.drawLine(vert)
        qp.setPen(targetpen)
        qp.drawEllipse(targ, 10, 10)
        qp.end()
Example #6
0
 def setJointCommands(self, commands):
     new_pan = round(
         self.deg2Pxl(commands[0], self.pan_deg_limits[0],
                      self.pan_deg_limits[1]))
     new_tilt = round(self.size - self.deg2Pxl(
         commands[1], self.tilt_deg_limits[0], self.tilt_deg_limits[1]))
     self.setState(QPoint(new_pan, new_tilt))
     self.update()
Example #7
0
 def mousePressEvent(self, event):
     '''
     Set the starting position for a drag event when the mouse button is pressed
     '''
     self.drag_droped_pos = QPoint(0, 0)
     self.drag_initiated = False
     if event.button() == Qt.LeftButton:
         self.drag_start_pos = event.pos()
     QTabBar.mousePressEvent(self, event)
Example #8
0
 def dragEnterEvent(self, event):
     '''
     Determine if the drag has entered a tab position from another tab position
     '''
     self.drag_droped_pos = QPoint(0, 0)
     mime_data = event.mimeData()
     formats = mime_data.formats()
     if 'action' in formats and mime_data.data('action') == 'application/tab-detach':
         event.acceptProposedAction()
     QTabBar.dragMoveEvent(self, event)
Example #9
0
 def setJointStates(self, positions):
     new_pan = round(
         self.deg2Pxl(positions[0], self.pan_deg_limits[0],
                      self.pan_deg_limits[1]))
     new_tilt = round(self.size - self.deg2Pxl(
         positions[1], self.tilt_deg_limits[0], self.tilt_deg_limits[1]))
     # Since this function is called at around 100 Hz, only update the QPushButton if the current position has significantly changed
     if (abs(new_pan - self.current_pos.x()) >= 1
             or abs(new_tilt - self.current_pos.y()) >= 1):
         self.current_pos = QPoint(new_pan, new_tilt)
         self.update()
Example #10
0
 def readSettings(self):
     if nm.settings().store_geometry:
         settings = nm.settings().qsettings(nm.settings().CFG_GUI_FILE)
         settings.beginGroup("editor")
         maximized = settings.value("maximized", 'false') == 'true'
         if maximized:
             self.showMaximized()
         else:
             self.resize(settings.value("size", QSize(800, 640)))
             self.move(settings.value("pos", QPoint(0, 0)))
         try:
             self.restoreState(settings.value("window_state"))
         except:
             import traceback
             print traceback.format_exc()
         settings.endGroup()
Example #11
0
    def __init__(self, parent=None):
        glformat = QGLFormat()
        glformat.setSampleBuffers(True)
        super(GLWidget, self).__init__(glformat, parent)

        self.setCursor(Qt.OpenHandCursor)
        self.setMouseTracking(True)

        self._modelview_matrix = numpy.identity(4)
        self._near = 0.001
        self._far = 100000.0
        self._fovy = 45.0
        self._radius = 5.0
        self._last_point_2d = QPoint()
        self._last_point_3d = [0.0, 0.0, 0.0]
        self._last_point_3d_ok = False
Example #12
0
 def setState(self, ev):
     pnt = QPoint(ev.x(), ev.y())
     # Since (0,0) is in the upper left corner, that means that increasingly negative Tilt values will be closer to the top of the push button; However,
     # However, it makes visual sense to flip this so that increasingly negative Tilt values are closer to the bottom of the push button; thus, the funky math... :)
     if (pnt.x() < self.pan_limits[0] or pnt.y() <
         (self.size - self.tilt_limits[1]) or pnt.x() > self.pan_limits[1]
             or pnt.y() > (self.size - self.tilt_limits[0])):
         return
     if self.state == pnt:
         return
     self.state = pnt
     self.update()
     if self.isChecked():
         cmd_x = self.pxl2Deg(self.state.x(), self.pan_deg_limits[0],
                              self.pan_deg_limits[1])
         cmd_y = -self.pxl2Deg(self.state.y(), self.tilt_deg_limits[0],
                               self.tilt_deg_limits[1])
         self.gui.name_map["pan"]["display"].setText("%.1f" % cmd_x)
         self.gui.name_map["tilt"]["display"].setText("%.1f" % cmd_y)
         self.gui.update_slider_bar("pan")
         self.gui.update_slider_bar("tilt")
Example #13
0
        def drawControl (self, element, opt, painter, widget=None):

#            print element
            if element == QStyle.CE_HeaderLabel:
                hv = widget
#                if not hv or hv.orientation() != Qt.Horizontal:
#                    return super(StateHistoryDialog.MyStyle, self).drawControl(element, opt, p, widget)
                header = opt

                if header.section < 3:
                    return super(StateHistoryDialog.MyStyle, self).drawControl(element, opt, painter, widget)

                painter.save()
                #// painter->translate(header->rect.topLeft())
                rect = header.rect.bottomLeft()
                painter.translate(QPoint(rect.x() + 10, rect.y() + 5))
#                print "drawControl"
                painter.rotate(-90)
                painter.drawText(0,0,header.text)
                painter.restore()
                return
#            return QProxyStyle::drawControl(element, option, painter, widget);
#            print "drawControl"
            return super(StateHistoryDialog.MyStyle, self).drawControl(element, opt, painter, widget)
Example #14
0
 def get_rectangular_polygon(self, pt1, pt2):
     return QPolygon(
         [pt1, QPoint(pt1.x(), pt2.y()), pt2,
          QPoint(pt2.x(), pt1.y())])
Example #15
0
def transformPointToRealWorldCoordinates(pt, map, image_size):
    map_size = QSize(map.map.info.width, map.map.info.height)
    vertically_flipped_point = QPoint(pt.x(), image_size.height() - pt.y() - 1)
    map_point = scalePoint(vertically_flipped_point, image_size, map_size)
    return QPointF(map.map.info.origin.position.x, map.map.info.origin.position.y) + \
            QPointF(map_point) * map.map.info.resolution
Example #16
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)
Example #17
0
class my_widget(QWidget):

    mouse_is_pressed = False
    cursor_pos = QPoint(0,0)
    cur_nradius = 0 #normalized radius
    cur_sector = 0

    def __init__  (self,*args):
        QWidget. __init__ (self,*args)

    def paintEvent(self,event=None):
	#global mouse_is_pressed

	w_height = self.frameGeometry().height()
	w_width = self.frameGeometry().width()
	if w_height > w_width:
	    diam = w_width
	else:
	    diam = w_height
	radius = int(diam / 2) - 10

	start_x = w_width/2 - radius
	start_y = w_height/2 - radius

	line1_x1 = w_width/2 + radius*0.707
	line1_x2 = w_width/2 - radius*0.707
	line1_y1 = w_height/2 - radius*0.707
	line1_y2 = w_height/2 + radius*0.707
	line2_x1 = w_width/2 - radius*0.707
	line2_x2 = w_width/2 + radius*0.707
	line2_y1 = line1_y1
	line2_y2 = line1_y2

        painter=QPainter()
        painter.begin(self)
        painter.setPen(QPen(Qt.black))
        painter.drawLine(line1_x1, line1_y1, line1_x2, line1_y2) #cross
	painter.drawLine(line2_x1, line2_y1, line2_x2, line2_y2)
	painter.drawEllipse(start_x,start_y , (radius*2), (radius*2))

	if self.mouse_is_pressed == True:
	    painter.setBrush(Qt.blue)
	    rad = self.get_radius(w_width, w_height, self.cursor_pos)
            pos = self.get_pos(w_width, w_height, self.cursor_pos)
	    if (radius < rad):
	        rad = radius
	    self.draw_arc(painter, w_width, w_height, pos, rad)
	    self.cur_nradius = rad*1.0/radius
	    self.cur_sector = pos
	else:
	    self.cur_nradius = 0.0
	    self.cur_sector = 0.0
        painter.end()
	#print self.mouse_is_pressed
        pass

    #get direction of mouse point
    def get_pos(self, w_width, w_height, cursor_pos):
	center_x = w_width/2
	center_y = w_height/2
	angle = math.atan2((center_x - cursor_pos.x()),(center_y - cursor_pos.y()))*180.0/math.pi
	angle = angle - 45
	if (angle<0):
		angle = 360+angle
	pos = int(angle/90) + 1
	if (pos>3):
		pos = 0
	return pos

    #get radius of mouse point
    def get_radius(self, w_width, w_height, cursor_pos):
	center_x = w_width/2
	center_y = w_height/2
	tmp_val = math.pow((center_x - cursor_pos.x()),2) + math.pow((center_y - cursor_pos.y()),2)
	rad = int(math.sqrt(tmp_val))
	return rad

    def draw_arc(self,qp, w_width, w_height, pos, rad):
	start_x = w_width/2 - rad
	start_y = w_height/2 - rad
	rectangle = QRect(start_x,start_y,(rad*2),(rad*2))
	qp.drawPie(rectangle, (45+90*pos)*16, 90*16)
	

    def mousePressEvent(self, QMouseEvent):
	self.cursor_pos = QMouseEvent.pos()
	self.mouse_is_pressed = True
	my_widget.update(self)

    def mouseMoveEvent(self, QMouseEvent):
	self.cursor_pos = QMouseEvent.pos()
	self.mouse_is_pressed = True

    def mouseReleaseEvent(self, QMouseEvent):
	self.cursor_pos = QMouseEvent.pos()
	self.mouse_is_pressed = False
	my_widget.update(self)
Example #18
0
    def __init__(self,
                 items=list(),
                 buttons=QDialogButtonBox.Cancel | QDialogButtonBox.Ok,
                 exclusive=False,
                 preselect_all=False,
                 title='',
                 description='',
                 icon='',
                 parent=None,
                 select_if_single=True,
                 checkitem1='',
                 checkitem2='',
                 closein=0,
                 store_geometry=''):
        '''
        Creates an input dialog.
        @param items: a list with strings
        @type items: C{list()}
        '''
        QDialog.__init__(self, parent=parent)
        self.setObjectName(' - '.join(['SelectDialog', utf8(items)]))

        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setObjectName("verticalLayout")
        self.verticalLayout.setContentsMargins(3, 3, 3, 3)

        # add filter row
        self.filter_field = EnhancedLineEdit(self)
        self.filter_field.setPlaceholderText("filter")
        self.filter_field.textChanged.connect(self._on_filter_changed)
        self.verticalLayout.addWidget(self.filter_field)

        if description:
            self.description_frame = QFrame(self)
            descriptionLayout = QHBoxLayout(self.description_frame)
            #      descriptionLayout.setContentsMargins(1, 1, 1, 1)
            if icon:
                self.icon_label = QLabel(self.description_frame)
                self.icon_label.setSizePolicy(QSizePolicy.Fixed,
                                              QSizePolicy.Fixed)
                self.icon_label.setPixmap(
                    QPixmap(icon).scaled(30, 30, Qt.KeepAspectRatio))
                descriptionLayout.addWidget(self.icon_label)
            self.description_label = QLabel(self.description_frame)
            self.description_label.setWordWrap(True)
            self.description_label.setText(description)
            descriptionLayout.addWidget(self.description_label)
            self.verticalLayout.addWidget(self.description_frame)

        # create area for the parameter
        self.content = MainBox(self)
        if items:
            self.scroll_area = QScrollArea(self)
            self.scroll_area.setFocusPolicy(Qt.NoFocus)
            self.scroll_area.setObjectName("scroll_area")
            self.scroll_area.setWidgetResizable(True)
            self.scroll_area.setWidget(self.content)
            self.verticalLayout.addWidget(self.scroll_area)

        self.checkitem1 = checkitem1
        self.checkitem1_result = False
        self.checkitem2 = checkitem2
        self.checkitem2_result = False

        # add select all option
        if not exclusive and items:
            self._ignore_next_toggle = False
            self.select_all_checkbox = QCheckBox('all entries')
            self.select_all_checkbox.setTristate(True)
            self.select_all_checkbox.stateChanged.connect(
                self._on_select_all_checkbox_stateChanged)
            self.verticalLayout.addWidget(self.select_all_checkbox)
            self.content.toggled.connect(self._on_main_toggle)
        if self.checkitem1:
            self.checkitem1_checkbox = QCheckBox(self.checkitem1)
            self.checkitem1_checkbox.stateChanged.connect(
                self._on_select_checkitem1_checkbox_stateChanged)
            self.verticalLayout.addWidget(self.checkitem1_checkbox)
        if self.checkitem2:
            self.checkitem2_checkbox = QCheckBox(self.checkitem2)
            self.checkitem2_checkbox.stateChanged.connect(
                self._on_select_checkitem2_checkbox_stateChanged)
            self.verticalLayout.addWidget(self.checkitem2_checkbox)
        if not items:
            spacerItem = QSpacerItem(1, 1, QSizePolicy.Expanding,
                                     QSizePolicy.Expanding)
            self.verticalLayout.addItem(spacerItem)

        self._close_timer = None
        self._closein = closein - 1
        if closein > 0:
            self.closein_label = QLabel("OK in %d sec..." % closein)
            self.closein_label.setAlignment(Qt.AlignRight)
            self.verticalLayout.addWidget(self.closein_label)
            self._close_timer = threading.Timer(1.0, self._on_close_timer)
            self._close_timer.start()

        # create buttons
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setObjectName("buttonBox")
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(buttons)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        self.verticalLayout.addWidget(self.buttonBox)

        # set the input fields
        if items:
            self.content.createFieldsFromValues(items, exclusive)
            if (select_if_single and len(items) == 1) or preselect_all:
                self.select_all_checkbox.setCheckState(Qt.Checked)

        if not items or len(items) < 7:
            self.filter_field.setVisible(False)

        # restore from configuration file
        self._geometry_name = store_geometry
        if store_geometry and nm.settings().store_geometry:
            settings = nm.settings().qsettings(nm.settings().CFG_GUI_FILE)
            settings.beginGroup(store_geometry)
            self.resize(settings.value("size", QSize(480, 320)))
            pos = settings.value("pos", QPoint(0, 0))
            if pos.x() != 0 and pos.y() != 0:
                self.move(pos)
            settings.endGroup()