Esempio n. 1
0
 def mousePressEvent(self, e: QMouseEvent) -> None:
     if self.actual_selection.value == 1:
         super(CustomQGraphicsView, self).mousePressEvent(e)
     elif self.actual_selection.value in [2, 3, 4, 5]:
         self.drawing = True
         self.previous_point = QPoint(int(e.position().x()),
                                      int(e.position().y()))
     elif self.actual_selection.value == 6:
         self.previous_point = self.mapToScene(
             QPoint(int(e.position().x()), int(e.position().y())))
         if not self.preparing:
             self.preparing = True
             self.prepare_points = list()
             self.prepare_points.append(self.previous_point)
         else:
             below_point: float = 5 / self.transform().m11()
             DrawTools.draw_simple_shape_to_scene(self,
                                                  self.prepare_points[-1],
                                                  self.previous_point,
                                                  to_gim=False)
             if fabs(self.previous_point.x() - self.prepare_points[0].x()) < below_point and \
                     fabs(self.previous_point.y() - self.prepare_points[0].y()) < below_point:
                 if len(self.prepare_points) <= 2:
                     items = self.scene().items()
                     for i in range(len(self.prepare_points)):
                         self.scene().removeItem(items[i])
                     self.preparing = False
                     return
                 DrawTools.draw_polygon(self, self.prepare_points)
                 self.preparing = False
             else:
                 self.prepare_points.append(self.previous_point)
Esempio n. 2
0
 def mouseMoveEvent(self, QMouseEvent):
     diff = QPoint(QMouseEvent.pos() - self.mouse_position)
     self.mouse_position = QMouseEvent.pos()
     self.scroll_area.verticalScrollBar().setValue(
         self.scroll_area.verticalScrollBar().value() - diff.y())
     self.scroll_area.horizontalScrollBar().setValue(
         self.scroll_area.horizontalScrollBar().value() - diff.x())
Esempio n. 3
0
    def updatePixmap(self, image, scaleFactor):
        if not self.lastDragPos.isNull():
            return

        self.pixmap = QPixmap.fromImage(image)
        self.pixmapOffset = QPoint()
        self.lastDragPosition = QPoint()
        self.pixmapScale = scaleFactor
        self.update()
Esempio n. 4
0
class Highlight(QObject):
    pos: QPoint = QPoint(0, 0),
    size: QPoint = QPoint(0, 0)

    def __iter__(self):
        return self

    def __next__(self):
        return self.next()
Esempio n. 5
0
    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.pixmapOffset += event.pos() - self.lastDragPos
            self.lastDragPos = QPoint()

            deltaX = (self.width() -
                      self.pixmap.width()) / 2 - self.pixmapOffset.x()
            deltaY = (self.height() -
                      self.pixmap.height()) / 2 - self.pixmapOffset.y()
            self.scroll(deltaX, deltaY)
Esempio n. 6
0
    def mouseMoveEvent(self, event):
        dx = event.x() - self.lastPos.x()
        dy = event.y() - self.lastPos.y()

        if event.buttons() & Qt.LeftButton:
            self.setXRotation(self.xRot + 8 * dy)
            self.setYRotation(self.yRot + 8 * dx)
        elif event.buttons() & Qt.RightButton:
            self.setXRotation(self.xRot + 8 * dy)
            self.setZRotation(self.zRot + 8 * dx)

        self.lastPos = QPoint(event.pos())
Esempio n. 7
0
 def show(self):
     super(QtBubbleLabel, self).show()
     x = self.parent().geometry().x()
     y = self.parent().geometry().y()
     x2 = self.parent().size().width()
     y2 = self.parent().size().height()
     startPos = QPoint(x + int(x2 / 2) - int(self.width() / 2),
                       y + int(y2 / 2))
     endPos = QPoint(x + int(x2 / 2) - int(self.width() / 2),
                     y + int(y2 / 2) - self.height() * 3 - 5)
     self.move(startPos)
     # 初始化动画
     self.initAnimation(startPos, endPos)
Esempio n. 8
0
 def __init__(self, scene: QGraphicsScene, parent: QMainWindow):
     QGraphicsView.__init__(self, scene, parent)
     self.crop_rect = QRect(QPoint(0, 0), QSize(0, 0))
     self.g_rect = QGraphicsRectItem(QRectF(self.crop_rect))
     self.setParent(parent)
     self.app = self.parent()
     self.crop_btn = self.parent().crop_button
     self.mouse_down = False
     self.g_rect.setPen(QPen(Qt.red, 1, Qt.SolidLine))
     self.g_rect.setBrush(QBrush(Qt.red, Qt.Dense6Pattern))
     self.mouse_pos = QPoint(0, 0)
     self.adjustment = ''
     self.annotation = False
def test_contextMenuEvent(skip_qtbot, canvas, mocker):
    mock_qmenu: MagicMock = mocker.patch("PySide6.QtWidgets.QMenu")

    event = MagicMock()
    event.globalPos.return_value = QPoint(100, 200)
    canvas._update_scale_variables()

    # Run
    canvas.contextMenuEvent(event)

    # Assert
    mock_qmenu.assert_any_call(canvas)
    mock_qmenu.assert_any_call('Area: First Tutorial Access', canvas)
    event.globalPos.assert_has_calls([call(), call()])
    mock_qmenu.return_value.exec_.assert_called_once_with(QPoint(100, 200))
Esempio n. 10
0
 def reset(self):
     self.crop_rect = QRect(QPoint(0, 0), QSize(0, 0))
     self.g_rect = QGraphicsRectItem(QRectF(self.crop_rect))
     self.g_rect.setPen(QPen(Qt.red, 1, Qt.SolidLine))
     self.g_rect.setBrush(QBrush(Qt.red, Qt.Dense6Pattern))
     self.setMouseTracking(False)
     self.unsetCursor()
     self.mouse_pos = QPoint(0, 0)
     self.adjustment = ''
     self.mouse_down = False
     if self.crop_btn.isChecked():
         self.app.reload()
         self.setCursor(Qt.CrossCursor)
     if self.annotation:
         self.setCursor(Qt.CrossCursor)
Esempio n. 11
0
    def _update_fixed_widgets(self):
        r = self.viewport().rect()
        for w, a in self.fixed_widgets.items():
            p = QPoint()

            if a & Qt.AlignHCenter:
                p.setX((r.width() - w.width()) / 2)
            elif a & Qt.AlignRight:
                p.setX(r.width() - w.width())

            if a & Qt.AlignVCenter:
                p.setY((r.height() - w.height()) / 2)
            elif a & Qt.AlignBottom:
                p.setY(r.height() - w.height())
            w.move(p)
Esempio n. 12
0
 def from_string(self, text, original_value):
     if isinstance(original_value, QColor):
         match = self.color_exp.match(text)
         return QColor(min(int(match.captured(1)), 255),
                       min(int(match.captured(2)), 255),
                       min(int(match.captured(3)), 255),
                       min(int(match.captured(4)), 255))
     if isinstance(original_value, QDate):
         value = QDate.fromString(text, Qt.ISODate)
         return value if value.isValid() else None
     if isinstance(original_value, QDateTime):
         value = QDateTime.fromString(text, Qt.ISODate)
         return value if value.isValid() else None
     if isinstance(original_value, QTime):
         value = QTime.fromString(text, Qt.ISODate)
         return value if value.isValid() else None
     if isinstance(original_value, QPoint):
         match = self.point_exp.match(text)
         return QPoint(int(match.captured(1)),
                       int(match.captured(2)))
     if isinstance(original_value, QRect):
         match = self.rect_exp.match(text)
         return QRect(int(match.captured(1)),
                      int(match.captured(2)),
                      int(match.captured(3)),
                      int(match.captured(4)))
     if isinstance(original_value, QSize):
         match = self.size_exp.match(text)
         return QSize(int(match.captured(1)),
                      int(match.captured(2)))
     if isinstance(original_value, list):
         return text.split(',')
     return type(original_value)(text)
Esempio n. 13
0
    def paintEvent(self, event):
        """
        Paint the widget.
        """
        super(WaTorGraph, self).paintEvent(event)

        painter = QPainter(self)

        fish, sharks = self._world.stats()

        shark = self.helper_calc_y_pos(sharks)
        fish = self.helper_calc_y_pos(fish)

        draw = ImageDraw.Draw(self._image)
        draw.line([(self._prev_tick, self._prev_shark),
                   (self._tick, shark)], (0, 0, 255), 2)
        draw.line([(self._prev_tick, self._prev_fish),
                   (self._tick, fish)], (0, 255, 0), 2)

        painter.drawImage(QPoint(0, 0), ImageQt(self._image))
        painter.end()

        self._prev_tick = self._tick
        self._prev_shark = shark
        self._prev_fish = fish
        self._tick += 2

        if self._tick >= self._widget_size.width():
            self.reset()
Esempio n. 14
0
 def message_box(self, message: str, buttons: int = 1) -> int:
     '''
     Message box with "Yes/No" or "OK" buttons. Defaults to "OK".\n
         Parameters:\n
             message (str): Message shown inside the message box.
             buttons (int): Amount of buttons, 1 - "OK" button, 2 - "Yes/No" buttons.
         Returns:\n
             choice (int): ID of the clicked button.
     '''
     pixmap = QPixmap(resource_path('icon.ico')).scaledToWidth(
         35, Qt.SmoothTransformation)
     msg_box = QMessageBox()
     msg_box.setFont(ui.font)
     msg_box.setText(message)
     if buttons == 2:
         msg_yes = msg_box.addButton(QMessageBox.Yes)
         msg_no = msg_box.addButton(QMessageBox.No)
         msg_yes.setText(self.dialog_yes)
         msg_no.setText(self.dialog_no)
         msg_yes.setProperty('class', 'button_yes')
         msg_no.setProperty('class', 'button_no')
     msg_box.setWindowFlags(Qt.Dialog | Qt.CustomizeWindowHint)
     msg_box.setIconPixmap(pixmap)
     with open(resource_path('style.css'), 'r') as file:
         msg_box.setStyleSheet(file.read())
     msg_box.move(ui.frameGeometry().center() -
                  QRect(QPoint(), msg_box.sizeHint()).center())
     choice = msg_box.exec_()
     return choice
Esempio n. 15
0
 def moveHueSelector(self, event):
     if event.buttons() == Qt.LeftButton:
         pos = event.pos().y() - 7
         if pos < 0: pos = 0
         if pos > 185: pos = 185
         self.ui.hue_selector.move(QPoint(7, pos))
         self.hsvChanged()
Esempio n. 16
0
    def _do_layout(self, rect, test_only):
        x = rect.x()
        y = rect.y()
        line_height = 0
        spacing = self.spacing()

        for item in self._item_list:
            style = item.widget().style()
            layout_spacing_x = style.layoutSpacing(QSizePolicy.PushButton,
                                                   QSizePolicy.PushButton,
                                                   Qt.Horizontal)
            layout_spacing_y = style.layoutSpacing(QSizePolicy.PushButton,
                                                   QSizePolicy.PushButton,
                                                   Qt.Vertical)
            space_x = spacing + layout_spacing_x
            space_y = spacing + layout_spacing_y
            next_x = x + item.sizeHint().width() + space_x
            if next_x - space_x > rect.right() and line_height > 0:
                x = rect.x()
                y = y + line_height + space_y
                next_x = x + item.sizeHint().width() + space_x
                line_height = 0

            if not test_only:
                item.setGeometry(QRect(QPoint(x, y), item.sizeHint()))

            x = next_x
            line_height = max(line_height, item.sizeHint().height())

        return y + line_height - rect.y()
Esempio n. 17
0
    def __init__(self, parent, dict, persepolis_setting):
        super().__init__(persepolis_setting)
        self.persepolis_setting = persepolis_setting
        self.dict = dict
        self.parent = parent

        # add support for other languages
        locale = str(self.persepolis_setting.value('settings/locale'))
        QLocale.setDefault(QLocale(locale))
        self.translator = QTranslator()
        if self.translator.load(':/translations/locales/ui_' + locale, 'ts'):
            QCoreApplication.installTranslator(self.translator)

        # connecting buttons
        self.open_pushButtun.clicked.connect(self.openFile)
        self.open_folder_pushButtun.clicked.connect(self.openFolder)
        self.ok_pushButton.clicked.connect(self.okButtonPressed)

        # labels
        # find gid
        gid = self.dict['gid']

        # get file_path from data base
        self.add_link_dict = self.parent.persepolis_db.searchGidInAddLinkTable(gid)
        file_path = self.add_link_dict['download_path']

        # save_as
        self.save_as_lineEdit.setText(file_path)
        self.save_as_lineEdit.setToolTip(file_path)

        # link
        link = str(self.dict['link'])
        self.link_lineEdit.setText(link)
        self.link_lineEdit.setToolTip(link)

        # file_name

        window_title = str(self.dict['file_name'])
        file_name = QCoreApplication.translate("after_download_src_ui_tr", "<b>File name</b>: ") + \
            window_title

        self.setWindowTitle(window_title)

        self.file_name_label.setText(file_name)

        # size
        size = QCoreApplication.translate("after_download_src_ui_tr", "<b>Size</b>: ") + str(self.dict['size'])
        self.size_label.setText(size)

        # disable link_lineEdit and save_as_lineEdit
        self.link_lineEdit.setEnabled(False)
        self.save_as_lineEdit.setEnabled(False)

        # set window size and position
        size = self.persepolis_setting.value(
            'AfterDownloadWindow/size', QSize(570, 290))
        position = self.persepolis_setting.value(
            'AfterDownloadWindow/position', QPoint(300, 300))
        self.resize(size)
        self.move(position)
Esempio n. 18
0
 def on_widget_place(self, widget: Widget):
     # print(f"on_widget_place", widget)
     native = widget._native_
     if native is not None:
         x, y = widget._rel_coord_
         native.pos = QPoint(x, y)
         native.size = QSize(*widget._phys_size_)
Esempio n. 19
0
 def setMousetoTitleBar(self):
     """ set the Mouse Cursor to Middel of Title Bar """
     t = self.ui.title_bar
     x = self.window.x() + t.pos().x() + int(t.width() / 2)
     y = self.window.y() + t.pos().y() + int(t.height() / 2)
     p = QPoint(x, y)
     QCursor.setPos(p)
     return p
Esempio n. 20
0
 def on_container_place(_, widget: "Widget"):
     # if widget._native_ is not None:
     assert (
         widget._native_ is not None
     ), f"{widget} was probably not built w/ on_container_build (._native_)"
     x, y = widget._rel_coord_
     widget._native_.pos = QPoint(x, y)
     widget._native_.size = QSize(*widget._phys_size_)
Esempio n. 21
0
    def dropEvent(self, event):
        if event.mimeData().hasText():
            mime = event.mimeData()
            pieces = mime.text().split()
            position = event.pos()
            hotSpot = QPoint()

            hotSpotPos = mime.data('application/x-hotspot').split(' ')
            if len(hotSpotPos) == 2:
                hotSpot.setX(hotSpotPos[0].toInt()[0])
                hotSpot.setY(hotSpotPos[1].toInt()[0])

            for piece in pieces:
                newLabel = DragLabel(piece, self)
                newLabel.move(position - hotSpot)
                newLabel.show()

                position += QPoint(newLabel.width(), 0)

            if event.source() in self.children():
                event.setDropAction(Qt.MoveAction)
                event.accept()
            else:
                event.acceptProposedAction()
        else:
            event.ignore()
Esempio n. 22
0
 def moveSVSelector(self, event):
     if event.buttons() == Qt.LeftButton:
         pos = event.pos()
         if pos.x() < 0: pos.setX(0)
         if pos.y() < 0: pos.setY(0)
         if pos.x() > 200: pos.setX(200)
         if pos.y() > 200: pos.setY(200)
         self.ui.selector.move(pos - QPoint(6, 6))
         self.hsvChanged()
Esempio n. 23
0
    def __init__(self, parent, gid, persepolis_setting):
        super().__init__(persepolis_setting)
        self.persepolis_setting = persepolis_setting
        self.parent = parent
        self.gid = gid
        self.status = None
        self.resume_pushButton.clicked.connect(self.resumePushButtonPressed)
        self.stop_pushButton.clicked.connect(self.stopPushButtonPressed)
        self.pause_pushButton.clicked.connect(self.pausePushButtonPressed)
        self.download_progressBar.setValue(0)
        self.limit_pushButton.clicked.connect(self.limitPushButtonPressed)

        self.limit_frame.setEnabled(False)
        self.limit_checkBox.toggled.connect(self.limitCheckBoxToggled)

        self.after_frame.setEnabled(False)
        self.after_checkBox.toggled.connect(self.afterCheckBoxToggled)

        self.after_pushButton.clicked.connect(self.afterPushButtonPressed)

        # add support for other languages
        locale = str(self.persepolis_setting.value('settings/locale'))
        QLocale.setDefault(QLocale(locale))
        self.translator = QTranslator()
        if self.translator.load(':/translations/locales/ui_' + locale, 'ts'):
            QCoreApplication.installTranslator(self.translator)

# check if limit speed activated by user or not
        add_link_dictionary = self.parent.persepolis_db.searchGidInAddLinkTable(
            gid)

        limit = str(add_link_dictionary['limit_value'])
        if limit != '0':
            limit_number = limit[:-1]
            limit_unit = limit[-1]
            self.limit_spinBox.setValue(float(limit_number))
            if limit_unit == 'K':
                self.after_comboBox.setCurrentIndex(0)
            else:
                self.after_comboBox.setCurrentIndex(1)
            self.limit_checkBox.setChecked(True)

        self.after_comboBox.currentIndexChanged.connect(
            self.afterComboBoxChanged)

        self.limit_comboBox.currentIndexChanged.connect(
            self.limitComboBoxChanged)

        self.limit_spinBox.valueChanged.connect(self.limitComboBoxChanged)

        # set window size and position
        size = self.persepolis_setting.value('ProgressWindow/size',
                                             QSize(595, 274))
        position = self.persepolis_setting.value('ProgressWindow/position',
                                                 QPoint(300, 300))
        self.resize(size)
        self.move(position)
Esempio n. 24
0
    def __init__(self, parent=None):
        super(MandelbrotWidget, self).__init__(parent)

        self.thread = RenderThread()
        self.pixmap = QPixmap()
        self.pixmapOffset = QPoint()
        self.lastDragPos = QPoint()

        self.centerX = DefaultCenterX
        self.centerY = DefaultCenterY
        self.pixmapScale = DefaultScale
        self.curScale = DefaultScale

        self.thread.renderedImage.connect(self.updatePixmap)

        self.setWindowTitle("Mandelbrot")
        self.setCursor(Qt.CrossCursor)
        self.resize(550, 400)
Esempio n. 25
0
    def __init__(self, parent, persepolis_setting):
        super().__init__(parent)

        self.persepolis_setting = persepolis_setting

        # set ui direction
        ui_direction = self.persepolis_setting.value('ui_direction')

        if ui_direction == 'rtl':
            self.setLayoutDirection(Qt.RightToLeft)

        elif ui_direction in 'ltr':
            self.setLayoutDirection(Qt.LeftToRight)

        # set size
        self.resize(QSize(400, 80))
        self.setFixedWidth(400)

        # show this widget as ToolTip widget
        self.setWindowFlags(Qt.ToolTip)

        # find bottom right position
        bottom_right_screen = QDesktopWidget().availableGeometry().bottomRight(
        )

        bottom_right_notification = QRect(QPoint(0, 0), QSize(410, 120))
        bottom_right_notification.moveBottomRight(bottom_right_screen)
        self.move(bottom_right_notification.topLeft())

        # get persepolis icon path
        icons = ':/' + \
            str(self.persepolis_setting.value('settings/icons')) + '/'

        notification_horizontalLayout = QHBoxLayout(self)

        # persepolis icon
        svgWidget = QtSvg.QSvgWidget(':/persepolis.svg')
        svgWidget.setFixedSize(QSize(64, 64))

        notification_horizontalLayout.addWidget(svgWidget)

        notification_verticalLayout = QVBoxLayout()

        # 2 labels for notification messages
        self.label1 = QLabel(self)
        self.label1.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.label1.setStyleSheet("font-weight: bold")
        self.label1.setWordWrap(True)

        self.label2 = QLabel(self)
        self.label2.setWordWrap(True)
        self.label2.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)

        notification_verticalLayout.addWidget(self.label1)
        notification_verticalLayout.addWidget(self.label2)
        notification_horizontalLayout.addLayout(notification_verticalLayout)
Esempio n. 26
0
class Textbox(QObject):
    """
    Textbox model.
    """
    super(QObject).__init__()
    pos: QPoint = QPoint(0, 0),
    size: QSize = QSize(0, 0)
    color: QColor = QColor(0, 0, 0, 255.0)
    font: QFont = QFont("Arial", pointSize=11, weight=1, italic=False)
    text: str = ""
Esempio n. 27
0
    def paint(self, painter: QPainter, option: QStyleOptionViewItem,
              index: QModelIndex) -> None:
        itemOption = QStyleOptionViewItem(option)

        # disable focus outline
        if itemOption.state & QStyle.State_HasFocus:
            itemOption.state ^= QStyle.State_HasFocus
        # hover whole row
        if index.row() == option.styleObject.hoverIndexRow:
            itemOption.state |= QStyle.State_MouseOver

        super().paint(painter, itemOption, index)

        # draw lines around numeric columns
        if index.column() in (5, 12):
            oldpen = painter.pen()
            painter.setPen(self.linepen)
            painter.drawLine(itemOption.rect.topRight() + QPoint(0, 0),
                             itemOption.rect.bottomRight() + QPoint(0, 0))
            painter.setPen(oldpen)
    def paintEvent(self, event):
        painter = QPainter(self)
        output_size = QSize()

        if self.mode == Mode.PngMode:
            output_size = self.zoomed_image.size()
            output_rect = QRect(QPoint(), output_size)
            output_rect.translate(self.rect().center() - output_rect.center())
            painter.drawImage(output_rect.topLeft(), self.zoomed_image)

        elif self.mode == Mode.SvgMode:
            output_size = self.svgRenderer.defaultSize()
            if self.zoom_scale != ZOOM_ORIGINAL_SCALE:
                zoom = float(self.zoom_scale) / ZOOM_ORIGINAL_SCALE
                output_size.scale(output_size.width() * zoom,
                                  output_size.height() * zoom,
                                  Qt.IgnoreAspectRatio)

            output_rect = QRect(QPoint(), output_size)
            output_rect.translate(self.rect().center() - output_rect.center())
            self.svgRenderer.render(painter, output_rect)

        self.setMinimumSize(output_size)
Esempio n. 29
0
def read_settings():
    """Read application settings.

    Returns
    -------
    settings : dict
        Settings values.
    """
    settings = {}
    settings["recent"] = QSettings().value("recent", [])
    settings["toolbar"] = QSettings().value("toolbar", True)
    settings["statusbar"] = QSettings().value("statusbar", True)
    settings["size"] = QSettings().value("size", QSize(700, 500))
    settings["pos"] = QSettings().value("pos", QPoint(100, 100))
    return settings
Esempio n. 30
0
    def __init__(self, parent: Qtw.QWidget):
        super(Patchcord, self).__init__(parent)
        self.setAttribute(Qt.WA_TransparentForMouseEvents)
        self.startPoint = QPoint(
            0,
            0)  # the names startPoint and endPoint are arbitrarily attributed
        self.endPoint = QPoint(0, 0)  # they do not correspond to in or out
        self.endPointIo = ""

        self.startPp = None
        self.endPp = None

        self.inpp = None
        self.outpp = None

        self.isHovered = True

        # self.raise_()
        self.show()

        if len(self.colors) < 1:
            self.colors = pcColors.copy()
        self.color = QColor(
            int(self.colors.pop(np.random.randint(len(self.colors))), 0))