Exemplo n.º 1
0
    def eventFilter(self, obj: QObject, event: QEvent) -> bool:
        """Event filter to process an event for the given destination.

        In this case, this widget listens for Enter events on the application level
        (during this widget's init, this eventFilter is installed on the app instance).

        When the destination object is a QWidget,
        we can try to update this widget's help_text with the destination widget's what's this help text.
        If there is no what's this text, we set the help_text back to its placeholderText.
        """
        if event.type() == QEvent.Enter:
            if isinstance(obj, QWidget):
                help_text = obj.whatsThis()
                # When the obj has help text, let's update the help text widget
                if help_text != "":
                    self._help_display.setText(help_text)
                    # Store a ref to the entered widget so we can maintain the help text if its children don't have any
                    self._cached_entered_widget = weakref.ref(obj)

        if event.type() == QEvent.Leave:
            if isinstance(obj, QWidget):
                # When we leave a widget, if it didn't have help text,
                # we want to check if the previously cached (entered) widget is its ancestor.
                # This will maintain the ancestor's help text in the help text widget when the child has not help text.
                if obj.whatsThis() == "":
                    # Revert to placeholder text when we have left a widget and the cached widget is not its ancestor
                    # (i.e. the previously entered widget with help text is not related).
                    if not self._is_child_of_previously_entered_widget_with_help_text(
                            obj):
                        self._help_display.setText(
                            self._help_display.placeholderText())

        return super(HelpWidget, self).eventFilter(obj, event)
Exemplo n.º 2
0
    def editorEvent(
        self,
        event: QtCore.QEvent,
        model: QtCore.QAbstractItemModel,
        option: QStyleOptionViewItem,
        index: QtCore.QModelIndex,
    ) -> bool:
        """Called when an event has occured in the editor.

        This can be used to customize how the delegate handles mouse/key events
        """
        if (event.type() == event.MouseButtonRelease
                and event.button() == Qt.RightButton):
            self.show_context_menu(index, model, event.globalPos(),
                                   option.widget)

        # if the user clicks quickly on the visibility checkbox, we *don't*
        # want it to be interpreted as a double-click.  We want the visibilty
        # to simply be toggled.
        if event.type() == event.MouseButtonDblClick:
            self.initStyleOption(option, index)
            style = option.widget.style()
            check_rect = style.subElementRect(
                style.SE_ItemViewItemCheckIndicator, option, option.widget)
            if check_rect.contains(event.pos()):
                cur_state = index.data(Qt.CheckStateRole)
                if model.flags(index) & Qt.ItemIsUserTristate:
                    state = Qt.CheckState((cur_state + 1) % 3)
                else:
                    state = Qt.Unchecked if cur_state else Qt.Checked
                return model.setData(index, state, Qt.CheckStateRole)
        # refer all other events to the QStyledItemDelegate
        return super().editorEvent(event, model, option, index)
Exemplo n.º 3
0
    def editorEvent(self, event: QtCore.QEvent,
                    model: QtCore.QAbstractItemModel,
                    option: 'QStyleOptionViewItem',
                    index: QtCore.QModelIndex) -> bool:
        decorationRect = option.rect

        if event.type() == QEvent.MouseButtonPress:
            item = index.model().data(index, Qt.UserRole)
            if isinstance(item, QVariant):
                return QStyledItemDelegate.editorEvent(self, event, model,
                                                       option, index)

            type = item['type']
            value = item['value']
            if type == 'device_activity':
                text_rect = calculate_text_rect(
                    value['device'], font=ResourceLoader().qt_font_text_xs)
                if calculate_middle_rect(decorationRect,
                                         text_rect.width(),
                                         text_rect.height(),
                                         x=110,
                                         y=15).contains(event.pos()):
                    print('点击了设备{device}'.format(device=value['device']))

        return QStyledItemDelegate.editorEvent(self, event, model, option,
                                               index)
Exemplo n.º 4
0
class CBEvent(QEvent):
    # allocate an event ID#
    EVENT_TYPE = QEvent.Type(QEvent.registerEventType())

    def __init__(self, result):
        QEvent.__init__(self, self.EVENT_TYPE)
        self.result = result
Exemplo n.º 5
0
 def __init__(self, queue, exceptions_in_main, fn, *args, **kwargs):
     QEvent.__init__(self, self.EVENT_TYPE)
     self.fn = fn
     self.args = args
     self.kwargs = kwargs
     self._returnval = queue
     # Whether to raise exceptions in the main thread or store them
     # for raising in the calling thread:
     self._exceptions_in_main = exceptions_in_main
Exemplo n.º 6
0
    def paintEvent(self, event: QEvent) -> None:
        color = self.colors[self._state]
        color = QColor(*(color.value))

        painter = QPainter(self)
        painter.setRenderHint(QPainter.HighQualityAntialiasing)
        painter.setPen(QPen(color, 2))
        painter.drawPolyline(self.coords)

        event.accept()
Exemplo n.º 7
0
 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)
Exemplo n.º 8
0
 def eventFilter(self, object: QLineEdit, event: QEvent):
     if event.type() == QEvent.FocusIn:
         object.setFrame(True)
         object.setReadOnly(False)
         return True
     if event.type() == QEvent.FocusOut:
         if object.text():
             object.setFrame(False)
         object.setReadOnly(True)
         return True
     return False
Exemplo n.º 9
0
class InvokeEvent(QEvent):
    """
    Generic callable containing QEvent
    """
    EVENT_TYPE = QEvent.Type(QEvent.registerEventType())

    def __init__(self, fn, *args, **kwargs):
        QEvent.__init__(self, InvokeEvent.EVENT_TYPE)
        self.fn = fn
        self.args = args
        self.kwargs = kwargs
Exemplo n.º 10
0
 def closeEvent(self, event: QtCore.QEvent):
     if self.close_confirm:
         reply = chisurf.widgets.MyMessageBox.question(
             self, 'Message',
             "Are you sure to close this fit?:\n%s" % self.fit.name,
             QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No)
         if reply == QtWidgets.QMessageBox.Yes:
             chisurf.console.execute('chisurf.macros.close_fit()')
         else:
             event.ignore()
     else:
         event.accept()
Exemplo n.º 11
0
class CallEvent(QEvent):
    """An event containing a request for a function call."""
    EVENT_TYPE = QEvent.Type(QEvent.registerEventType())

    def __init__(self, queue, exceptions_in_main, fn, *args, **kwargs):
        QEvent.__init__(self, self.EVENT_TYPE)
        self.fn = fn
        self.args = args
        self.kwargs = kwargs
        self._returnval = queue
        # Whether to raise exceptions in the main thread or store them
        # for raising in the calling thread:
        self._exceptions_in_main = exceptions_in_main
Exemplo n.º 12
0
    def sceneEventFilter(self, event: QtCore.QEvent) -> bool:
        if MaskTool.sceneEventFilter(self, event):
            return True
        # Mouse press starts drawing
        if event.type() == QtCore.QEvent.GraphicsSceneMousePress and event.button() == QtCore.Qt.LeftButton:
            with self.parent.window.changeTracker("bucket fill in mask"):
                self.fillColor(event.pos().x(), event.pos().y())
                self.parent.save()
            # accept the event
            return True

        # don't accept the event, so that others can accept it
        return False
Exemplo n.º 13
0
 def _handle_edit(self, event: QtCore.QEvent):
     """Handle closing edit box and redisplayin label"""
     if event.type() == QtCore.QEvent.Type.KeyPress:
         key = event.key()
         if key in (QtCore.Qt.Key.Key_Return, QtCore.Qt.Key.Key_Enter):
             if not self.edit.hasAcceptableInput():
                 self.setCurrentWidget(self.label)
                 return
             self.label.setText(self.edit.text())
             self.setCurrentWidget(self.label)
             self.valueChanged.emit(self.label.text())
         if key == QtCore.Qt.Key.Key_Escape:
             self.setCurrentWidget(self.label)
     elif event.type() == QtCore.QEvent.FocusOut:
         self.setCurrentWidget(self.label)
Exemplo n.º 14
0
    def event(self, e: QEvent) -> bool:
        '''
        Event

        Parameters
        ----------
        e : QEvent

        Returns
        -------
        value : bool
        '''
        state = self.d.dragging_state
        if state == DragState.inactive:
            # Normally we would check here, if the left mouse button is pressed.
            # But from QT version 5.12.2 on the mouse events from
            # QEvent.NonClientAreaMouseButtonPress return the wrong mouse
            # button The event always returns Qt.RightButton even if the left
            # button is clicked.
            if e.type() == QEvent.NonClientAreaMouseButtonPress:
                if QT_VERSION_TUPLE >= (5, 12, 2):
                    # and QGuiApplication.mouseButtons().testFlag(Qt.LeftButton ...
                    logger.debug('FloatingWidget.event Event.NonClientAreaMouseButtonPress %s', e.type())
                    self.d.set_state(DragState.mouse_pressed)
                elif QGuiApplication.mouseButtons() == Qt.LeftButton:
                    logger.debug('FloatingWidget.event Event.NonClientAreaMouseButtonPress %s', e.type())
                    self.d.set_state(DragState.mouse_pressed)
        elif state == DragState.mouse_pressed:
            if e.type() == QEvent.NonClientAreaMouseButtonDblClick:
                logger.debug('FloatingWidget.event QEvent.NonClientAreaMouseButtonDblClick')
                self.d.set_state(DragState.inactive)
            elif e.type() == QEvent.Resize:
                # If the first event after the mouse press is a resize event, then
                # the user resizes the window instead of dragging it around.
                # But there is one exception. If the window is maximized,
                # then dragging the window via title bar will cause the widget to
                # leave the maximized state. This in turn will trigger a resize event.
                # To know, if the resize event was triggered by user via moving a
                # corner of the window frame or if it was caused by a windows state
                # change, we check, if we are not in maximized state.
                if not self.isMaximized():
                    self.d.set_state(DragState.inactive)
        elif state == DragState.floating_widget:
            if e.type() == QEvent.NonClientAreaMouseButtonRelease:
                logger.debug('FloatingWidget.event QEvent.NonClientAreaMouseButtonRelease')
                self.d.title_mouse_release_event()

        return super().event(e)
Exemplo n.º 15
0
 def event(self, event: QEvent):
     if event.type() == QEvent.WindowActivate:
         index = self.components.currentRow()
         self.components.clear()
         self.components.addItems(list(map(str, self.get_parameters.keys())))
         self.components.setCurrentRow(index)
     return super().event(event)
Exemplo n.º 16
0
 def event(self, event: QEvent):
     if event.type() == QEvent.WindowActivate and self.isVisible():
         self.update_profile_list()
         self.update_spacing()
         self.multiple_files_chk.setChecked(
             self._settings.get("multiple_files_widget", False))
     return super().event(event)
Exemplo n.º 17
0
 def _handle_label(self, event: QtCore.QEvent):
     """Display QLineEdit if label is double clicked"""
     if event.type() == QtCore.QEvent.Type.MouseButtonDblClick:
         self.edit.setText(self.label.text())
         self.setCurrentWidget(self.edit)
         self.edit.selectAll()
         self.edit.setFocus()
Exemplo n.º 18
0
    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)
Exemplo n.º 19
0
    def eventFilter(self, watched: QObject, event: QEvent) -> bool:
        '''
        Eventfilter

        Parameters
        ----------
        watched : QObject
            Unused
        event : QEvent

        Returns
        -------
        value : bool
        '''
        #pylint: disable=unused-argument
        if event.type() == QEvent.MouseButtonRelease:
            logger.debug('MouseButtonRelease')
            if self.d.dragging_state == DragState.floating_widget:
                qapp = QApplication.instance()
                qapp.removeEventFilter(self)
                logger.debug('FloatingWidget.eventFilter QEvent.MouseButtonRelease')
                self.finish_dragging()
                self.d.title_mouse_release_event()

        return False
Exemplo n.º 20
0
 def mouseReleaseEvent(self, event: QEvent):
     """Show QColorPopup picker when the user clicks on the swatch."""
     if event.button() == Qt.LeftButton:
         initial = QColor(*(255 * self._color).astype('int'))
         popup = QColorPopup(self, initial)
         popup.colorSelected.connect(self.setColor)
         popup.show_right_of_mouse()
Exemplo n.º 21
0
    def event(self, e: QEvent) -> bool:
        '''
        Emits titleChanged signal if title change event occurs

        Parameters
        ----------
        e : QEvent

        Returns
        -------
        value : bool
        '''
        if e.type() == QEvent.WindowTitleChange:
            title = self.windowTitle()
            if self.d.tab_widget:
                self.d.tab_widget.setText(title)
            if self.d.toggle_view_action:
                self.d.toggle_view_action.setText(title)
            if self.d.dock_area:
                # update tabs menu
                self.d.dock_area.mark_title_bar_menu_outdated()

            self.title_changed.emit(title)

        return super().event(e)
Exemplo n.º 22
0
 def event(self, event: QEvent):
     if event.type() == QEvent.WindowActivate:
         # update combobox for segmentation
         self.update_combo_box(self.choose_profile, self._settings.segmentation_profiles)
         # update combobox for pipeline
         self.update_combo_box(self.choose_pipe, self._settings.segmentation_pipelines)
         self.update_tooltips()
     return super().event(event)
Exemplo n.º 23
0
    def changeEvent(self, event: QEvent):
        """Change event handler.

        Args:
            event (QEvent): Event.
        """
        if event.type() == QEvent.StyleChange:
            self.setColor(qrainbowstyle.getCurrentPalette().COLOR_ACCENT_4)
Exemplo n.º 24
0
    def event(self, event: QEvent) -> bool:
        if event.type() == QEvent.WindowActivate:
            if self.settings.image is not None:
                self.channel_select.change_channels_num(
                    self.settings.image.channels)
            self.refresh_measurements()

        return super().event(event)
Exemplo n.º 25
0
 def changeEvent(self, event: QEvent):
     """Change event handler.
     Args:
         event (QEvent): Event.
     """
     if event.type() == QEvent.StyleChange:
         self.setHtml(qrainbowstyle.rainbowize(OpenStreetMapsHtml.html))
     return super().changeEvent(event)
Exemplo n.º 26
0
 def test_label_spec_info(self, botimport):
     bot, dialog = botimport
     pos = dialog.label_info.rect().center()
     event = QEnterEvent(pos, pos, pos)
     dialog.label_info.enterEvent(event)
     assert dialog.label_info.dlg.isVisible()
     event = QEvent(QEvent.Leave)
     dialog.label_info.leaveEvent(event)
     assert not dialog.label_info.dlg.isVisible()
Exemplo n.º 27
0
 def dropEvent(self, event: QtCore.QEvent):
     for url in event.mimeData().urls():
         print(url)
         url = str(url.toString()).strip()
         if url.startswith("file:///"):
             url = url[len("file:///"):]
         if url.startswith("file:"):
             url = url[len("file:"):]
         self.loadFile(url)
Exemplo n.º 28
0
    def eventFilter(self, qobject: QObject, event: QEvent) -> bool:
        if event.type() == QEvent.ToolTipChange and isinstance(
                qobject, QWidget):
            tooltip = qobject.toolTip()
            if tooltip and not qt_might_be_rich_text(tooltip):
                qobject.setToolTip(f'<qt>{html.escape(tooltip)}</qt>')
                return True

        return super().eventFilter(qobject, event)
Exemplo n.º 29
0
 def dropEvent(self, event: QtCore.QEvent) -> None:
     """Event is called after dragEnterEvent."""
     for url in event.mimeData().urls():  # pragma: no cover
         self.url = url
         filename = self.url.path()
         if os.path.isfile(filename):
             try:
                 self.add_mesh(pyvista.read(filename))
             except IOError as exception:
                 print(str(exception))
Exemplo n.º 30
0
 def dropEvent(self, event: QtCore.QEvent):
     if self.load_thread is not None:
         self.load_thread.join()
     for url in event.mimeData().urls():
         url = str(url.toString()).strip()
         if url.startswith("file:///"):
             url = url[len("file:///"):]
         if url.startswith("file:"):
             url = url[len("file:"):]
         self.loadUrl(url, reset=True)