def enterEvent(self, event): """Override to show tooltips instantly.""" if self.toolTip(): pos = self.mapToGlobal(self.contentsRect().center()) QToolTip.showText(pos, self.toolTip(), self) super().enterEvent(event)
def _show_step_tooltip(self): QToolTip.showText( self.mapToGlobal( QPoint(self.x()+self.width()/2, self.y()-2*self.height())), 'Single step: '+str(self.singleStep) + '\nPage step: '+str(self.pageStep), self, self.rect(), 1000)
def show_mouse_toast(message): # Creates a text with empty space to get the height of the rendered text - this is used # to provide the same offset for the tooltip, scaled relative to the current resolution and zoom. font_metrics = QFontMetrics(QFont(" ")) # The height itself is divided by 2 just to reduce the offset so that the tooltip is # reasonably position relative to the cursor QToolTip.showText(QCursor.pos() + QPoint(font_metrics.height() / 2, 0), message)
def mouseMoveEvent(self, ev): if not self._image_item.width() or not self._image_item.height(): super().mouseMoveEvent(ev) return pos = ev.pos() posaux = self._image_item.mapFromDevice(ev.pos()) if posaux.x() < 0 or posaux.x() >= self._image_item.width() or \ posaux.y() < 0 or posaux.y() >= self._image_item.height(): super().mouseMoveEvent(ev) return pos_scene = self._view.mapSceneToView(pos) x = round(pos_scene.x()) y = round(pos_scene.y()) if self.xAxisChannel and self._last_xaxis_data is not None: maxx = len(self._last_xaxis_data) - 1 x = x if x < maxx else maxx valx = self._last_xaxis_data[x] else: valx = x if self.yAxisChannel and self._last_yaxis_data is not None: maxy = len(self._last_yaxis_data) - 1 y = y if y < maxy else maxy valy = self._last_yaxis_data[y] else: valy = y txt = self.format_tooltip.format(valx, valy) QToolTip.showText(self.mapToGlobal(pos), txt, self, self.geometry(), 5000) super().mouseMoveEvent(ev)
def show_state_channel(self, event): """ Show the State Channel Tooltip and copy address to clipboard This is intended to replicate the behavior of the "middle click" from EDM. If the parent is not PCDSSymbolBase and does not have a valid State Channel nothing will be displayed. """ from ..vacuum.base import PCDSSymbolBase p = find_ancestor_for_widget(self, PCDSSymbolBase) if not p: return state_suffix = getattr(p, '_state_suffix', None) if not state_suffix: return addr = "{}{}".format(p.channelsPrefix, state_suffix) QToolTip.showText(event.globalPos(), addr) # If the address has a protocol, strip it out before putting it on the # clipboard. copy_text = remove_protocol(addr) clipboard = QApplication.clipboard() clipboard.setText(copy_text) event = QEvent(QEvent.Clipboard) QApplication.instance().sendEvent(clipboard, event)
def _show_tooltip(self, pos, pln='x'): unit = 'rad' if self.is_orb: names = self._csorb.bpm_nicknames posi = self._csorb.bpm_pos unit = 'm' elif pln == 'x': names = self._csorb.ch_nicknames posi = self._csorb.ch_pos else: names = self._csorb.cv_nicknames posi = self._csorb.cv_pos graph = self.graph[pln] curve = graph.curveAtIndex(0) posx = curve.scatter.mapFromScene(pos).x() if self._csorb.isring: posx = posx % self._csorb.circum ind = _np.argmin(_np.abs(_np.array(posi) - posx)) posy = curve.scatter.mapFromScene(pos).y() sca, prf = functions.siScale(posy) txt = '{0:s}, y = {1:.3f} {2:s}'.format(names[ind], sca * posy, prf + unit) QToolTip.showText(graph.mapToGlobal(pos.toPoint()), txt, graph, graph.geometry(), 500)
def mouseMoveEvent(self, event): """Reimplement mouseMoveEvent.""" pos = event.pos() posx = self.curve.scatter.mapFromScene(pos).x() posx = posx % self._c0 ind = _np.argmin(_np.abs(_np.array(self._x_data)-posx)) txt = '{0:s}, x = {1:.3f} m'.format(self.tooltips[ind], posx) QToolTip.showText( self.mapToGlobal(pos), txt, self, self.geometry(), 500) super().mouseMoveEvent(event)
def row_changed(self, row): item = self.completion_list[row] if len(item['documentation']) > 0: # TODO: LSP - Define an UI element to display the documentation # self.textedit.show_calltip( # item['detail'], item['documentation'], color='#daa520', # at_point=item['point']) pass else: QToolTip.hideText()
def hide_tooltip_if_necessary(self, key): """Hide calltip when necessary""" try: calltip_char = self.get_character(self.calltip_position) before = self.is_cursor_before(self.calltip_position, char_offset=1) other = key in (Qt.Key_ParenRight, Qt.Key_Period, Qt.Key_Tab) if calltip_char not in ('?', '(') or before or other: QToolTip.hideText() except (IndexError, TypeError): QToolTip.hideText()
def eventFilter(self, obj, event): ret = super(BasePlot, self).eventFilter(obj, event) if utilities.is_qt_designer(): if event.type() == QEvent.Enter: QToolTip.showText( self.mapToGlobal(self.rect().center()), 'Edit plot curves via Right-Click and select "Edit Curves..."', self, QRect(0, 0, 200, 100), 4000) return ret
def _show_tooltip_time(self, pos): graph = self.graph_time curve = graph.curveAtIndex(0) posx = curve.scatter.mapFromScene(pos).x() times = curve.getData()[0] if times is None: return ind = _np.argmin(_np.abs(times - posx)) txt = f'index = {ind:d}' QToolTip.showText(graph.mapToGlobal(pos.toPoint()), txt, graph, graph.geometry(), 500)
def show_calltip(self, title, text, signature=False, color='#2D62FF', at_line=None, at_position=None, at_point=None): """Show calltip""" if text is None or len(text) == 0: return # Saving cursor position: if at_position is None: at_position = self.get_position('cursor') self.calltip_position = at_position # Preparing text: if signature: text, wrapped_textlines = self._format_signature(text) else: if isinstance(text, list): text = "\n ".join(text) text = text.replace('\n', '<br>') if len(text) > self.calltip_size: text = text[:self.calltip_size] + " ..." # Formatting text font = self.font() size = font.pointSize() family = font.family() format1 = '<div style=\'font-family: "%s"; font-size: %spt; color: %s\'>'\ % (family, size, color) format2 = '<div style=\'font-family: "%s"; font-size: %spt\'>'\ % (family, size-1 if size > 9 else size) tiptext = format1 + ('<b>%s</b></div>' % title) + '<hr>' + \ format2 + text + "</div>" # Showing tooltip at cursor position: cx, cy = self.get_coordinates('cursor') if at_point is not None: cx, cy = at_point.x(), at_point.y() if at_line is not None: cx = 5 cursor = QTextCursor(self.document().findBlockByNumber(at_line - 1)) cy = self.cursorRect(cursor).top() point = self.mapToGlobal(QPoint(cx, cy)) point = self.calculate_real_position(point) point.setY(point.y() + font.pointSize() + 5) if signature: self.calltip_widget.show_tip(point, tiptext, wrapped_textlines) else: QToolTip.showText(point, tiptext)
def event(self, event: QEvent): if event.type() == QEvent.ToolTip and self.components: # text = str(self.component) text_list = [] for el in self.components: if self.settings.component_is_chosen(el): text_list.append("☑{}".format(el)) else: text_list.append("☐{}".format(el)) QToolTip.showText(event.globalPos(), " ".join(text_list)) return super().event(event)
def hide(self): """Override Qt method.""" self.completion_position = None self.completion_list = None self.clear() self.textedit.setFocus() tooltip = getattr(self.textedit, 'tooltip_widget', None) if tooltip: tooltip.hide() QListWidget.hide(self) QToolTip.hideText()
def update_warning(self): """ Updates the icon and tip based on the validity of the array content. """ widget = self._button_warning if not self.is_valid(): tip = _('Array dimensions not valid') widget.setIcon(ima.icon('MessageBoxWarning')) widget.setToolTip(tip) QToolTip.showText(self._widget.mapToGlobal(QPoint(0, 5)), tip) else: self._button_warning.setToolTip('')
def keyPressEvent(self, event): """Override Qt method.""" QToolTip.hideText() ctrl = event.modifiers() & Qt.ControlModifier if event.key() in [Qt.Key_Enter, Qt.Key_Return]: if ctrl: self.process_text(array=False) else: self.process_text(array=True) self.accept() else: super(ArrayBuilderDialog, self).keyPressEvent(event)
def clear_coords(self): """ Reset coord display and mouse tracking variables. If hold_coords is active (True), make changes only to indicate that the mouse is no longer over viewer. """ if self.hold_coords: return if QToolTip.text() == self.mouse_value: QToolTip.hideText() self.x_mouse = None self.y_mouse = None self.coord_label.setText('') self.statusBar().showMessage(self.status_message)
def eventFilter(self, obj, event): ret = super(BasePlot, self).eventFilter(obj, event) if utilities.is_qt_designer(): if event.type() == QEvent.Enter: QToolTip.showText( self.mapToGlobal(self.rect().center()), 'Edit plot curves via Right-Click and select "Edit Curves..."', self, QRect(0, 0, 200, 100), 4000) else: # Somehow super here is not invoking the PyDMPrimitiveWidget # eventFilter ret = PyDMPrimitiveWidget.eventFilter(self, obj, event) return ret
def mouseMoveEvent(self, ev): unit = 'urad' pos = ev.pos() posx = self.curve.scatter.mapFromScene(pos).x() posx = posx % self.c0 ind = _np.argmin(_np.abs(_np.array(self.xdata) - posx)) posy = self.curve.scatter.mapFromScene(pos).y() sca, prf = functions.siScale(posy) txt = '{0:s}, y = {1:.3f} {2:s}'.format(self.tooltip_names[ind], sca * posy, prf + unit) QToolTip.showText(self.mapToGlobal(pos), txt, self, self.geometry(), 500)
def keyPressEvent(self, event): """ Qt override. """ QToolTip.hideText() ctrl = event.modifiers() & Qt.ControlModifier if event.key() in [Qt.Key_Enter, Qt.Key_Return]: if ctrl: self.process_text(array=False) else: self.process_text(array=True) self.accept() else: QDialog.keyPressEvent(self, event)
def __init__(self, text_edit, hide_timer_on=False, as_tooltip=False): """ Create a call tip manager that is attached to the specified Qt text edit widget. """ assert isinstance(text_edit, (QTextEdit, QPlainTextEdit)) super(CallTipWidget, self).__init__(None, Qt.ToolTip) self.app = QCoreApplication.instance() self.as_tooltip = as_tooltip self.hide_timer_on = hide_timer_on self.tip = None self._hide_timer = QBasicTimer() self._text_edit = text_edit # Setup if sys.platform == 'darwin': # This keeps the hints below other applications self.setWindowFlags(Qt.SplashScreen) else: self.setWindowFlags(Qt.ToolTip | Qt.FramelessWindowHint) self.setTextInteractionFlags(Qt.TextSelectableByMouse) self.setFont(text_edit.document().defaultFont()) self.setForegroundRole(QPalette.ToolTipText) self.setBackgroundRole(QPalette.ToolTipBase) self.setPalette(QToolTip.palette()) self.setAlignment(Qt.AlignLeft) self.setIndent(1) self.setFrameStyle(QFrame.NoFrame) self.setMargin(1 + self.style().pixelMetric( QStyle.PM_ToolTipLabelFrameWidth, None, self))
def show_calltip(self, title, text, signature=False, color='#2D62FF', at_line=None, at_position=None, at_point=None): """Show calltip""" if text is None or len(text) == 0: return # Saving cursor position: if at_position is None: at_position = self.get_position('cursor') self.calltip_position = at_position # Preparing text: if signature: text, wrapped_textlines = self._format_signature(text) else: if isinstance(text, list): text = "\n ".join(text) text = text.replace('\n', '<br>') if len(text) > self.calltip_size: text = text[:self.calltip_size] + " ..." # Formatting text font = self.font() size = font.pointSize() family = font.family() format1 = '<div style=\'font-family: "%s"; font-size: %spt; color: %s\'>'\ % (family, size, color) format2 = '<div style=\'font-family: "%s"; font-size: %spt\'>'\ % (family, size-1 if size > 9 else size) tiptext = format1 + ('<b>%s</b></div>' % title) + '<hr>' + \ format2 + text + "</div>" # Showing tooltip at cursor position: cx, cy = self.get_coordinates('cursor') if at_point is not None: cx, cy = at_point.x(), at_point.y() if at_line is not None: cx = 5 cursor = QTextCursor(self.document().findBlockByNumber(at_line-1)) cy = self.cursorRect(cursor).top() point = self.mapToGlobal(QPoint(cx, cy)) point = self.calculate_real_position(point) point.setY(point.y()+font.pointSize()+5) if signature: self.calltip_widget.show_tip(point, tiptext, wrapped_textlines) else: QToolTip.showText(point, tiptext)
def hide(self, focus_to_parent=True): """Override Qt method.""" self.completion_position = None self.completion_list = None self.clear() # Used to control when to give focus to its parent. # This is necessary to have a better fix than the initially # proposed for issue spyder-ide/spyder#11502. if focus_to_parent: self.textedit.setFocus() tooltip = getattr(self.textedit, 'tooltip_widget', None) if tooltip: tooltip.hide() QListWidget.hide(self) QToolTip.hideText()
def event(self, e): if (e.type() == QEvent.ToolTip and self._qt_viewer.viewer.tooltip.visible): QToolTip.showText(e.globalPos(), self._qt_viewer.viewer.tooltip.text, self) if e.type() == QEvent.Close: # when we close the MainWindow, remove it from the instances list try: _QtMainWindow._instances.remove(self) except ValueError: pass if e.type() in {QEvent.WindowActivate, QEvent.ZOrderChange}: # upon activation or raise_, put window at the end of _instances try: inst = _QtMainWindow._instances inst.append(inst.pop(inst.index(self))) except ValueError: pass return super().event(e)
def show_address_tooltip(self, event): """ Show the PyDMTooltip and copy address to clipboard This is intended to replicate the behavior of the "middle click" from EDM. If the QWidget does not have a valid PyDMChannel nothing will be displayed """ channels_method = getattr(self, 'channels', None) if channels_method is None: return channels = channels_method() if not channels: logger.debug('Widget has no channels to display tooltip') return addrs = [] no_proto_addrs = [] for ch in channels: addr = ch.address if not addr: continue addrs.append(addr) no_proto_addrs.append(remove_protocol(addr)) tooltip = os.linesep.join(addrs) clipboard_text = " ".join(no_proto_addrs) QToolTip.showText(event.globalPos(), tooltip) # If the address has a protocol, strip it out before putting it on the # clipboard. clipboard = QApplication.clipboard() mode = clipboard.Clipboard if platform.system() == 'Linux': # Mode Selection is only valid for X11. mode = clipboard.Selection clipboard.setText(clipboard_text, mode=mode) event = QEvent(QEvent.Clipboard) self.app.sendEvent(clipboard, event)
def show_address_tooltip(self, event): """ Show the PyDMTooltip and copy address to clipboard This is intended to replicate the behavior of the "middle click" from EDM. If the QWidget does not have a valid PyDMChannel nothing will be displayed """ if not len(self._channels): logger.warning("Object %r has no PyDM Channels", self) return addr = self.channels()[0].address QToolTip.showText(event.globalPos(), addr) # If the address has a protocol, strip it out before putting it on the # clipboard. copy_text = remove_protocol(addr) clipboard = QApplication.clipboard() clipboard.setText(copy_text) event = QEvent(QEvent.Clipboard) self.app.sendEvent(clipboard, event)
def _show_tooltip(self, pos): names = self._csorb.bpm_nicknames cname = self._csorb.ch_nicknames + self._csorb.cv_nicknames if self._csorb.isring: cname += [ 'RF', ] posi = self._csorb.bpm_pos graph = self.graph curve = graph.curveAtIndex(0) posx = curve.scatter.mapFromScene(pos).x() if self._csorb.isring: posx = posx % self._csorb.circum ind = _np.argmin(_np.abs(_np.array(posi) - posx)) posy = curve.scatter.mapFromScene(pos).y() indy = int(posy // self.spbox.value()) indy = max(min(indy, len(cname) - 1), 0) # sca, prf = functions.siScale(posy) txt = 'BPM = {0:s}, Corr = {1:s}'.format(names[ind], cname[indy]) QToolTip.showText(graph.mapToGlobal(pos.toPoint()), txt, graph, graph.geometry(), 500)
def wheelEvent(self, event: QWheelEvent) -> None: """Switch function by mouse wheel. + Set zoom bar value. + Set select mode. """ p = event.angleDelta() if QApplication.keyboardModifiers() == Qt.ShiftModifier: value = p.y() elif p.x() != 0: value = p.x() elif p.y() != 0: value = self.prefer.scale_factor_option * (1 if p.y() > 0 else -1) value += self.zoom_value() self.set_zoom_bar(value) return else: return tags = ("Points", "Links") mode = (self.selection_mode() + (-1 if value > 0 else 1)) % len(tags) self.selection_mode_wheel(mode) QToolTip.showText(event.globalPos(), f"Selection mode: {tags[mode]}", self) event.accept()
def __init__(self, parent=None, as_tooltip=False): """ Shows tooltips that can be styled with the different themes. """ super(ToolTipWidget, self).__init__(None, Qt.ToolTip) # Variables self.completion_doc = None self._url = '' self.app = QCoreApplication.instance() self.as_tooltip = as_tooltip self.tip = None self._timer_hide = QTimer() self._text_edit = parent # Setup # This keeps the hints below other applications if sys.platform == 'darwin': self.setWindowFlags(Qt.SplashScreen) else: self.setWindowFlags(Qt.ToolTip | Qt.FramelessWindowHint) self._timer_hide.setInterval(500) self.setTextInteractionFlags(Qt.TextSelectableByMouse) self.setTextInteractionFlags(Qt.TextBrowserInteraction) self.setOpenExternalLinks(False) self.setForegroundRole(QPalette.ToolTipText) self.setBackgroundRole(QPalette.ToolTipBase) self.setPalette(QToolTip.palette()) self.setAlignment(Qt.AlignLeft) self.setIndent(1) self.setFrameStyle(QFrame.NoFrame) style = self.style() delta_margin = style.pixelMetric(QStyle.PM_ToolTipLabelFrameWidth, None, self) self.setMargin(1 + delta_margin) # Signals self.linkHovered.connect(self._update_hover_html_link_style) self._timer_hide.timeout.connect(self.hide) QApplication.instance().applicationStateChanged.connect( self._should_hide)
def __init__(self, text_edit, hide_timer_on=False): """ Create a call tip manager that is attached to the specified Qt text edit widget. """ assert isinstance(text_edit, (QTextEdit, QPlainTextEdit)) super(CallTipWidget, self).__init__(None, Qt.ToolTip) self.app = QCoreApplication.instance() self.hide_timer_on = hide_timer_on self._hide_timer = QBasicTimer() self._text_edit = text_edit self.setFont(text_edit.document().defaultFont()) self.setForegroundRole(QPalette.ToolTipText) self.setBackgroundRole(QPalette.ToolTipBase) self.setPalette(QToolTip.palette()) self.setAlignment(Qt.AlignLeft) self.setIndent(1) self.setFrameStyle(QFrame.NoFrame) self.setMargin(1 + self.style().pixelMetric(QStyle.PM_ToolTipLabelFrameWidth, None, self))
def __init__(self, text_edit, hide_timer_on=False): """ Create a call tip manager that is attached to the specified Qt text edit widget. """ assert isinstance(text_edit, (QTextEdit, QPlainTextEdit)) super(CallTipWidget, self).__init__(None, Qt.ToolTip) self.app = QCoreApplication.instance() self.hide_timer_on = hide_timer_on self._hide_timer = QBasicTimer() self._text_edit = text_edit self.setFont(text_edit.document().defaultFont()) self.setForegroundRole(QPalette.ToolTipText) self.setBackgroundRole(QPalette.ToolTipBase) self.setPalette(QToolTip.palette()) self.setAlignment(Qt.AlignLeft) self.setIndent(1) self.setFrameStyle(QFrame.NoFrame) self.setMargin(1 + self.style().pixelMetric( QStyle.PM_ToolTipLabelFrameWidth, None, self))
def __init__(self, parent=None, as_tooltip=False): """ Shows tooltips that can be styled with the different themes. """ super(ToolTipWidget, self).__init__(parent, Qt.ToolTip) # Variables self.app = QCoreApplication.instance() self.as_tooltip = as_tooltip self.tip = None # Setup self.setForegroundRole(QPalette.ToolTipText) self.setBackgroundRole(QPalette.ToolTipBase) self.setPalette(QToolTip.palette()) self.setAlignment(Qt.AlignLeft) self.setIndent(1) self.setFrameStyle(QFrame.NoFrame) style = self.style() delta_margin = style.pixelMetric(QStyle.PM_ToolTipLabelFrameWidth, None, self) self.setMargin(1 + delta_margin)
def mouse_move(self, event): """ Event handler for matplotlib motion_notify_event. Updates coord display and vars. :param event: matplotlib event. """ # Check if mouse is in widget but not on plot if not event.inaxes: self.is_mouse_over = False self.clear_coords() return mouse_pos = QCursor.pos() self.is_mouse_over = True # If hold_coords is active, return if self.hold_coords: return # Get x and y of the pixel under the mouse x, y = [int(event.xdata + 0.5), int(event.ydata + 0.5)] self.x_mouse, self.y_mouse = [x, y] # Create coord display string if self._slice_index is not None: string = "({:1.0f}, {:1.0f}, {:1.0f})".format(x, y, self._slice_index) else: string = "({:1.0f}, {:1.0f})".format(x, y) self.mouse_value = "" # If viewer has a layer. if len(self.visible_layers()) > 0: arr = self.first_visible_layer().state.get_sliced_data() if 0 <= y < arr.shape[0] and 0 <= x < arr.shape[1]: # if x and y are in bounds. Note: x and y are swapped in array. # get value and check if wcs is obtainable # WCS: if len(self.figure.axes) > 0: wcs = self.figure.axes[0].wcs.celestial if wcs is not None: # Check the number of axes in the WCS and add to string ra = dec = None if wcs.naxis == 3 and self.slice_index is not None: ra, dec, wave = wcs.wcs_pix2world([[x, y, self._slice_index]], 0)[0] elif wcs.naxis == 2: ra, dec = wcs.wcs_pix2world([[x, y]], 0)[0] if ra is not None and dec is not None: string = string + " " + self._coords_format_function(ra, dec) # Pixel Value: v = arr[y][x] if self.cubeviz_unit is not None: wave = self.cubeviz_layout.get_wavelength(self.slice_index) v = self.cubeviz_unit.convert_value(v, wave=wave) unit_string = "" if self.component_unit_label: unit_string = "[{0}]".format(self.component_unit_label) if 0.001 <= abs(v) <= 1000 or abs(v) == 0.0: value_string = "{0:.3f} ".format(v) else: value_string = "{0:.3e} ".format(v) self.mouse_value = value_string + unit_string string = value_string + string # Add a gap to string and add to viewer. string += " " self._dont_update_status = True self.statusBar().clearMessage() self._dont_update_status = False self.coord_label.setText(string) if self._is_tooltip_on: if self.mouse_value: QToolTip.showText(mouse_pos, "...", self) QToolTip.showText(mouse_pos, self.mouse_value, self) else: QToolTip.showText(mouse_pos, "...", self) QToolTip.showText(mouse_pos, " ", self) return
def postprocess_keyevent(self, event): """Process keypress event""" ShellBaseWidget.postprocess_keyevent(self, event) if QToolTip.isVisible(): _event, _text, key, _ctrl, _shift = restore_keyevent(event) self.hide_tooltip_if_necessary(key)
def hide(self): QToolTip.hideText() QListWidget.hide(self) self.textedit.setFocus()
def show_tip(self, tip=""): """Show tip""" QToolTip.showText(self.mapToGlobal(self.pos()), tip, self)
def mouseReleaseEvent(self, event): QToolTip.showText(self.mapToGlobal(QPoint(0, self.height())), self._tip_text)
def mousePressEvent(self, event): QToolTip.hideText()