Ejemplo n.º 1
0
 def mouseMoveEvent(self, event):
     try:
         delta = QPoint(event.globalPos() - self.oldPos)
         self.move(self.x() + delta.x(), self.y() + delta.y())
         self.oldPos = event.globalPos()
     except (TypeError, AttributeError):
         pass
Ejemplo n.º 2
0
 def on_customContextMenuRequested(self, pos: QPoint):
     item = self.model().index(self.rowAt(pos.y()), 0).data()
     try:
         item = int(item)
         self.context_menu_requested.emit(item)
     except ValueError:
         pass
Ejemplo n.º 3
0
    def readSettings(self, settings):
        qapp = QApplication.instance()

        # get the saved window geometry
        window_size = settings.get('MainWindow/size')
        if not isinstance(window_size, QSize):
            window_size = QSize(*window_size)
        window_pos = settings.get('MainWindow/position')
        if not isinstance(window_pos, QPoint):
            window_pos = QPoint(*window_pos)
        if settings.has('MainWindow/font'):
            font_string = settings.get('MainWindow/font').split(',')
            font = QFontDatabase().font(font_string[0], font_string[-1],
                                        int(font_string[1]))
            qapp.setFont(font)

        # reset font for ipython console to ensure it stays monospace
        self.ipythonconsole.console.reset_font()

        # make sure main window is smaller than the desktop
        desktop = QDesktopWidget()

        # this gives the maximum screen number if the position is off screen
        screen = desktop.screenNumber(window_pos)

        # recalculate the window size
        desktop_geom = desktop.availableGeometry(screen)
        w = min(desktop_geom.size().width(), window_size.width())
        h = min(desktop_geom.size().height(), window_size.height())
        window_size = QSize(w, h)

        # and position it on the supplied desktop screen
        x = max(window_pos.x(), desktop_geom.left())
        y = max(window_pos.y(), desktop_geom.top())
        if x + w > desktop_geom.right():
            x = desktop_geom.right() - w
        if y + h > desktop_geom.bottom():
            y = desktop_geom.bottom() - h
        window_pos = QPoint(x, y)

        # set the geometry
        self.resize(window_size)
        self.move(window_pos)

        # restore window state
        if settings.has('MainWindow/state'):
            if not self.restoreState(settings.get('MainWindow/state'),
                                     SAVE_STATE_VERSION):
                logger.warning(
                    "The previous layout of workbench is not compatible with this version, reverting to default layout."
                )
        else:
            self.setWindowState(Qt.WindowMaximized)

        # read in settings for children
        AlgorithmInputHistory().readSettings(settings)
        for widget in self.widgets:
            if hasattr(widget, 'readSettingsIfNotDone'):
                widget.readSettingsIfNotDone(settings)
Ejemplo n.º 4
0
    def setCrosshairPos(self, pos):
        """
        Places the crosshair at a specific  location in the widget.  This is generally
        used when updating color values, and passing them back to the color widget.

        This is in LOCAL space
        """
        # get crosshair direction
        #main_widget = getWidgetAncestorByName(self, "ColorInputWidget")
        direction = self.getDirection()
        # set cross hair pos
        if direction == Qt.Horizontal:
            pos = QPoint(pos.x(), 0)
            self.setPos(pos.x(), 0)
        elif direction == Qt.Vertical:
            pos = QPoint(0, pos.y())
            self.setPos(0, pos.y())
Ejemplo n.º 5
0
    def readSettings(self, settings):
        qapp = QApplication.instance()
        qapp.setAttribute(Qt.AA_UseHighDpiPixmaps)
        if hasattr(Qt, 'AA_EnableHighDpiScaling'):
            qapp.setAttribute(Qt.AA_EnableHighDpiScaling,
                              settings.get('high_dpi_scaling'))

        # get the saved window geometry
        window_size = settings.get('MainWindow/size')
        if not isinstance(window_size, QSize):
            window_size = QSize(*window_size)
        window_pos = settings.get('MainWindow/position')
        if not isinstance(window_pos, QPoint):
            window_pos = QPoint(*window_pos)
        if settings.has('MainWindow/font'):
            font_string = settings.get('MainWindow/font').split(',')
            font = QFontDatabase().font(font_string[0], font_string[-1],
                                        int(font_string[1]))
            qapp.setFont(font)

        # make sure main window is smaller than the desktop
        desktop = QDesktopWidget()

        # this gives the maximum screen number if the position is off screen
        screen = desktop.screenNumber(window_pos)

        # recalculate the window size
        desktop_geom = desktop.availableGeometry(screen)
        w = min(desktop_geom.size().width(), window_size.width())
        h = min(desktop_geom.size().height(), window_size.height())
        window_size = QSize(w, h)

        # and position it on the supplied desktop screen
        x = max(window_pos.x(), desktop_geom.left())
        y = max(window_pos.y(), desktop_geom.top())
        if x + w > desktop_geom.right():
            x = desktop_geom.right() - w
        if y + h > desktop_geom.bottom():
            y = desktop_geom.bottom() - h
        window_pos = QPoint(x, y)

        # set the geometry
        self.resize(window_size)
        self.move(window_pos)

        # restore window state
        if settings.has('MainWindow/state'):
            self.restoreState(settings.get('MainWindow/state'))
        else:
            self.setWindowState(Qt.WindowMaximized)

        # read in settings for children
        AlgorithmInputHistory().readSettings(settings)
        for widget in self.widgets:
            if hasattr(widget, 'readSettings'):
                widget.readSettings(settings)
Ejemplo n.º 6
0
    def test_plot_clicked(self, setup, qtbot, variables):
        # test that clicking on the plot highlights the nearest plot in the viewer

        self.plotWidget.setXAxisRange(
            None)  # ensure all points visible in plotting area

        pts = self.plotWidget.dataItem.scatter.points()
        idx = random.randint(0, len(pts) - 1)

        pos = pts[idx].pos()
        scenePos = self.plotWidget.viewBoxes[0].mapViewToScene(pos)
        scenePos = QPoint(
            *[int(round(x)) for x in [scenePos.x(), scenePos.y()]])

        size = pts[idx].size() // 2
        sizePad = 2  # don't know why this is necessary
        size += sizePad
        pos = QPoint(scenePos.x() + size, scenePos.y() + size)

        class MockMouseEvent:
            # mouse clicks aren't propogated into the pyqtgraph graphicsscene
            # so make a mock one at the right point
            def __init__(self, scenePos):
                self.sp = scenePos

            def scenePos(self):
                return self.sp

        qtbot.wait(variables.wait)
        with qtbot.waitSignal(self.plotWidget.currentPointChanged):
            qtbot.mouseMove(self.plot, pos=pos, delay=variables.mouseDelay)
        qtbot.wait(variables.wait)

        event = MockMouseEvent(scenePos)
        signals = [(self.plotWidget.pointSelected, 'pointSelected'),
                   (self.viewer.currentItemChanged, 'currentItemChanged')]

        with qtbot.waitSignals(signals):
            self.plotWidget.plotClicked(event)
Ejemplo n.º 7
0
    def readSettings(self, settings):
        qapp = QApplication.instance()
        qapp.setAttribute(Qt.AA_UseHighDpiPixmaps)
        if hasattr(Qt, 'AA_EnableHighDpiScaling'):
            qapp.setAttribute(Qt.AA_EnableHighDpiScaling, settings.get('high_dpi_scaling'))

        # get the saved window geometry
        window_size = settings.get('MainWindow/size')
        if not isinstance(window_size, QSize):
            window_size = QSize(*window_size)
        window_pos = settings.get('MainWindow/position')
        if not isinstance(window_pos, QPoint):
            window_pos = QPoint(*window_pos)

        # make sure main window is smaller than the desktop
        desktop = QDesktopWidget()

        # this gives the maximum screen number if the position is off screen
        screen = desktop.screenNumber(window_pos)

        # recalculate the window size
        desktop_geom = desktop.screenGeometry(screen)
        w = min(desktop_geom.size().width(), window_size.width())
        h = min(desktop_geom.size().height(), window_size.height())
        window_size = QSize(w, h)

        # and position it on the supplied desktop screen
        x = max(window_pos.x(), desktop_geom.left())
        y = max(window_pos.y(), desktop_geom.top())
        window_pos = QPoint(x, y)

        # set the geometry
        self.resize(window_size)
        self.move(window_pos)

        # restore window state
        if settings.has('MainWindow/state'):
            self.restoreState(settings.get('MainWindow/state'))
        else:
            self.setWindowState(Qt.WindowMaximized)

        # read in settings for children
        AlgorithmInputHistory().readSettings(settings)
        for widget in self.widgets:
            if hasattr(widget, 'readSettings'):
                widget.readSettings(settings)
Ejemplo n.º 8
0
    def readSettings(self, settings):
        qapp = QApplication.instance()
        qapp.setAttribute(Qt.AA_UseHighDpiPixmaps)
        if hasattr(Qt, 'AA_EnableHighDpiScaling'):
            qapp.setAttribute(Qt.AA_EnableHighDpiScaling,
                              settings.get('main/high_dpi_scaling'))

        # get the saved window geometry
        window_size = settings.get('main/window/size')
        if not isinstance(window_size, QSize):
            window_size = QSize(*window_size)
        window_pos = settings.get('main/window/position')
        if not isinstance(window_pos, QPoint):
            window_pos = QPoint(*window_pos)

        # make sure main window is smaller than the desktop
        desktop = QDesktopWidget()

        # this gives the maximum screen number if the position is off screen
        screen = desktop.screenNumber(window_pos)

        # recalculate the window size
        desktop_geom = desktop.screenGeometry(screen)
        w = min(desktop_geom.size().width(), window_size.width())
        h = min(desktop_geom.size().height(), window_size.height())
        window_size = QSize(w, h)

        # and position it on the supplied desktop screen
        x = max(window_pos.x(), desktop_geom.left())
        y = max(window_pos.y(), desktop_geom.top())
        window_pos = QPoint(x, y)

        # set the geometry
        self.resize(window_size)
        self.move(window_pos)

        # restore window state
        if settings.has('main/window/state'):
            self.restoreState(settings.get('main/window/state'))
        else:
            self.setWindowState(Qt.WindowMaximized)

        # have algorithm dialogs do their thing
        AlgorithmInputHistory().readSettings(settings)
Ejemplo n.º 9
0
class NormalController(BaseController):
    def __init__(self, viewer):
        super().__init__(viewer)
        self.name = 'Normal'
        self.lastPos = None

    def mousePressEvent(self, event: QMouseEvent) -> None:
        super().mousePressEvent(event)
        self.lastPos = QPoint(event.pos())

    def mouseDoubleClickEvent(self, event: QMouseEvent) -> None:
        x, y, z = [event.pos().x(), event.pos().y(), 1]
        origin = self.viewer.origin_from_click(x, y, z)
        ray = self.viewer.ray_from_click(x, y, z)

        self.viewer.intersect_elements(origin, ray)

    def mouseMoveEvent(self, event: QMouseEvent) -> None:
        if self.lastPos is None:
            return

        dx = event.x() - self.lastPos.x()
        dy = event.y() - self.lastPos.y()
        smoothness = max(self.viewer.smoothness, 0.1)

        # viewer.world.setToIdentity()
        if event.buttons() == Qt.LeftButton:
            self.viewer.rotate(alpha=dy / smoothness,
                               beta=0,
                               gamma=dx / smoothness)

        elif event.buttons() == Qt.RightButton:
            self.viewer.rotate(alpha=dy / smoothness,
                               beta=dx / smoothness,
                               gamma=0)

        elif event.buttons() == Qt.MiddleButton:
            off_center = self.viewer.off_center[2]
            distance_x = off_center / self.viewer.width()
            distance_y = off_center / self.viewer.height()

            self.viewer.translate(x=-distance_x * dx, y=distance_y * dy, z=0)

        self.lastPos = QPoint(event.pos())
Ejemplo n.º 10
0
    def handle_action(self, item, pkg_name, action_name, update=False):
        widget = item.widget
        item.setText("0-" + item.text())
        method = getattr(self.installer, action_name)
        self._remove_list.append((pkg_name, item))
        self._warn_dialog = None
        if item.npe_version != 1:
            # show warning pop up dialog
            message = trans._(
                'When installing/uninstalling npe2 plugins, you must restart napari for UI changes to take effect.'
            )
            self._warn_dialog = WarnPopup(text=message, )

            delta_x = 75
            global_point = widget.action_button.mapToGlobal(
                widget.action_button.rect().topLeft())
            global_point = QPoint(global_point.x() - delta_x, global_point.y())
            self._warn_dialog.move(global_point)

        if action_name == "install":
            if update:
                if hasattr(item, 'latest_version'):
                    pkg_name += f"=={item.latest_version}"

                widget.set_busy(trans._("updating..."), update)
                widget.action_button.setDisabled(True)
            else:
                widget.set_busy(trans._("installing..."), update)

            method([pkg_name])
            if self._warn_dialog:
                self._warn_dialog.exec_()
            self.scrollToTop()
        elif action_name == "uninstall":
            widget.set_busy(trans._("uninstalling..."), update)
            widget.update_btn.setDisabled(True)
            method([pkg_name])
            if self._warn_dialog:
                self._warn_dialog.exec_()
            self.scrollToTop()
        elif action_name == "cancel":
            widget.set_busy(trans._("cancelling..."), update)
            method((pkg_name, ))
Ejemplo n.º 11
0
def PosToArray(pos: QtCore.QPoint) -> np.ndarray:
    return np.array([pos.x(), pos.y()])
Ejemplo n.º 12
0
class Microscope(QWidget):
    roiClicked = Signal(int, int)

    def __init__(self, parent=None):
        super(Microscope, self).__init__(parent)

        self.setMinimumWidth(300)
        self.setMinimumHeight(300)
        self.image = QImage('image.jpg')
        self.clicks = []
        self.center = QPoint(self.image.size().width() / 2,
                             self.image.size().height() / 2)
        self.drawBoxes = False
        self.start = QPoint(0, 0)
        self.end = QPoint(1, 1)
        self.yDivs = 5
        self.xDivs = 5
        self.color = False
        self.fps = 5
        self.scaleBar = False
        self.crop = []
        self.scale = []

        self.url = 'http://localhost:9998/jpg/image.jpg'

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.updateImage)

        self.downloader = Downloader(self)
        self.downloader.imageReady.connect(self.updateImageData)

    def updatedImageSize(self):
        if self.image.size() != self.minimumSize():
            self.setMinimumSize(self.image.size())
            self.center = QPoint(self.image.size().width() / 2,
                                 self.image.size().height() / 2)

    def acquire(self, start=True):
        self.downloader.setUrl(self.url)
        if start:
            self.timer.start(1000.0 / self.fps)
        else:
            self.timer.stop()

    def paintBoxes(self, painter):
        rect = QRect(
            self.start.x(),
            self.start.y(),
            self.end.x() - self.start.x(),
            self.end.y() - self.start.y(),
        )
        painter.setPen(QColor.fromRgb(0, 255, 0))
        painter.drawRect(rect)
        # Now draw the lines for the boxes in the rectangle.
        x1 = self.start.x()
        y1 = self.start.y()
        x2 = self.end.x()
        y2 = self.end.y()
        inc_x = (x2 - x1) / self.xDivs
        inc_y = (y2 - y1) / self.yDivs
        lines = time.perf_counter()
        for i in range(1, self.xDivs):
            painter.drawLine(x1 + i * inc_x, y1, x1 + i * inc_x, y2)
        for i in range(1, self.yDivs):
            painter.drawLine(x1, y1 + i * inc_y, x2, y1 + i * inc_y)
        mid = time.perf_counter()

        # Now draw the color overlay thing if requested
        rects = time.perf_counter()
        if self.color:
            brushColor = QColor(0, 255, 0, 20)
            brush = QBrush(brushColor)
            painter.setBrush(brush)
            painter.setPen(QColor.fromRgb(0, 255, 0))
            for i in range(0, self.xDivs):
                for j in range(0, self.yDivs):
                    alpha = i / self.yDivs * 255
                    if True:  # j % 2 == 0:
                        brushColor.setAlpha(alpha / 2)
                        brushColor.setGreen(255)
                    else:
                        brushColor.setAlpha(255 / 2)
                        brushColor.setGreen(alpha)

                    brush.setColor(brushColor)
                    painter.setBrush(brush)
                    rect = QRect(x1 + i * inc_x, y1 + j * inc_y, inc_x, inc_y)
                    painter.drawRect(rect)
        rects2 = time.perf_counter()

    def paintEvent(self, event):
        tic = time.perf_counter()
        painter = QPainter(self)
        rect = event.rect()
        painter.drawImage(rect, self.image, rect)
        painter.setPen(QColor.fromRgb(255, 0, 0))
        #painter.drawPoints(self.clicks)
        if self.drawBoxes:
            self.drawBoxes(painter)
        # Draw the center mark
        painter.setPen(QColor.fromRgb(255, 0, 0))
        painter.drawLine(self.center.x() - 20, self.center.y(),
                         self.center.x() + 20, self.center.y())
        painter.drawLine(self.center.x(),
                         self.center.y() - 20, self.center.x(),
                         self.center.y() + 20)

        # Draw the scale bar
        if self.scaleBar:
            painter.setPen(QColor.fromRgb(40, 40, 40))
            painter.setFont(QFont("Arial", 30))
            scaleRect = QRect(10, 420, 200, 30)
            painter.drawText(scaleRect, Qt.AlignCenter, "10 nm")
            pen = painter.pen()
            pen.setWidth(5)
            painter.setPen(pen)
            painter.drawLine(10, 460, 210, 460)

        toc = time.perf_counter()

    def mousePressEvent(self, event):
        pos = event.pos()
        self.roiClicked.emit(pos.x(), pos.y())
        self.clicks.append(pos)
        self.start = pos
        self.end = pos
        self.update()

    def mouseMoveEvent(self, event):
        self.end = event.pos()
        self.update()

    def sizeHint(self):
        return QSize(400, 400)

    def updateImage(self):
        """ Request an updated image asynchronously. """
        self.downloader.downloadData()

    def updateImageData(self, image):
        """ Triggered when the new image is ready, update the view. """
        self.image.loadFromData(image, 'JPG')
        if len(self.crop) == 4:
            self.image = self.image.copy(self.crop[0], self.crop[1],
                                         self.crop[2], self.crop[3])
        if len(self.scale) == 2:
            if self.scale[0] > 0:
                self.image = self.image.scaledToWidth(self.scale[0])
            elif self.scale[1] > 0:
                self.image = self.image.scaledToHeight(self.scale[1])

        self.updatedImageSize()
        self.update()

    def resizeImage(self):
        if len(self.crop) == 4:
            self.image = self.image.copy(self.crop[0], self.crop[1],
                                         self.crop[2], self.crop[3])
        if len(self.scale) == 2:
            if self.scale[0] > 0:
                self.image = self.image.scaledToWidth(self.scale[0])
            elif self.scale[1] > 0:
                self.image = self.image.scaledToHeight(self.scale[1])

    def readFromDict(self, settings):
        """ Read the settings from a Python dict. """
        if settings.has_key('url'):
            self.url = settings['url']
        if settings.has_key('fps'):
            self.fps = settings['fps']
        if settings.has_key('xDivs'):
            self.xDivs = settings['xDivs']
        if settings.has_key('yDivs'):
            self.yDivs = settings['yDivs']
        if settings.has_key('color'):
            self.color = settings['color']
        if settings.has_key('scaleW'):
            self.scale = [settings['scaleW'], 0]
        if settings.has_key('scaleH'):
            if len(self.scale) == 2:
                self.scale[1] = settings['scaleW']
            else:
                self.scale = [0, settings['scaleW']]

    def writeToDict(self):
        """ Write the widget's settings to a Python dict. """
        settings = {
            'url': self.url,
            'fps': self.fps,
            'xDivs': self.xDivs,
            'yDivs': self.yDivs,
            'color': self.color
        }
        if len(self.scale) == 2:
            settings['scaleW'] = self.scale[0]
            settings['scaleH'] = self.scale[1]
        return settings

    def readSettings(self, settings):
        """ Read the settings for this microscope instance. """
        self.url = settings.value('url', 'http://localhost:9998/jpg/image.jpg')
        print(f'url: {self.url}')
        self.fps = settings.value('fps', 5, type=int)
        self.xDivs = settings.value('xDivs', 5, type=int)
        self.yDivs = settings.value('yDivs', 5, type=int)
        self.color = settings.value('color', False, type=bool)
        if settings.value('scaleW', -1, type=int) >= 0:
            self.scale = [
                settings.value('scaleW', 0, type=int),
                settings.value('scaleH', 0, type=int)
            ]
            self.resizeImage()

    def writeSettings(self, settings):
        """ Write the settings for this microscope instance. """
        settings.setValue('url', self.url)
        settings.setValue('fps', self.fps)
        settings.setValue('xDivs', self.xDivs)
        settings.setValue('yDivs', self.yDivs)
        settings.setValue('color', self.color)
        if len(self.scale) == 2:
            settings.setValue('scaleW', self.scale[0])
            settings.setValue('scaleH', self.scale[1])
Ejemplo n.º 13
0
 def calc_offset(self, p: QPoint):
     offset_x = p.x() - int(self.viewport().width() / 2)
     offset_y = p.y() - int(self.viewport().height() / 2)
     return QPoint(offset_x, offset_y)
Ejemplo n.º 14
0
def QPoint_to_point(p: QtCore.QPoint) -> Point2:
    return Point2(p.x(), p.y())
Ejemplo n.º 15
0
    def _pickColor(self, pos, constrain_to_picker=True):
        """
        picks the the current color displayed on screen at
        the current location of the cursor

        Args:
            pos (QPoint): Global pos
            constrain_to_pick (bool): determines whether or not the crosshair
                should be forced to remain inside of the picker while the user
                is selecting.
        """
        # preflight check (cursor)
        # forces the cursor to remain inside of the color picker
        # TODO Removing bouncing
        """
        display is bouncing when reaching ends as it snaps back to the last
        position in space.  It also cannot get the final 0/1 values =
        """
        if constrain_to_picker is True:
            cursor_sector_dict = checkMousePos(pos, self)
            if cursor_sector_dict["INSIDE"] is False:
                top_left = self.mapToGlobal(self.pos())
                top = top_left.y()
                left = top_left.x()
                right = left + self.geometry().width()
                bottom = top + self.geometry().height()

                if cursor_sector_dict["NORTH"] is True:
                    pos.setY(top + 1)
                if cursor_sector_dict["EAST"] is True:
                    pos.setX(right - 1)
                if cursor_sector_dict["SOUTH"] is True:
                    pos.setY(bottom - 1)
                if cursor_sector_dict["WEST"] is True:
                    pos.setX(left + 1)

                QCursor.setPos(pos)

        # self.scene().rgba_crosshair_item.hide()
        # get pixel data
        desktop = QApplication.desktop().winId()
        screen = QApplication.primaryScreen()
        pixmap = screen.grabWindow(
            desktop,
            pos.x(), pos.y(),
            1, 1
        )
        img = pixmap.toImage()
        color = QColor(img.pixel(0, 0))

        # if pure black recurse
        # if color.valueF() == 0:
        # TODO
        """
        Grabbing color of picker because fails
        """
        if color.valueF() < .0001:
            self._black_select = True
            pos = QPoint(pos.x() + 1, pos.y() + 1)
            return self._pickColor(pos)

        return color
Ejemplo n.º 16
0
 def mouseMoveEvent(self, event):
     if self.window_moving and not self.isMaximized() and not self.isFullScreen():
         delta = QPoint(event.globalPos() - self.win_old_pos)
         self.move(self.x() + delta.x(), self.y() + delta.y())
         self.win_old_pos = event.globalPos()
         self.setWindowOpacity(0.5)