Python PyQt5.QtCore.QRect() Examples

The following are 30 code examples for showing how to use PyQt5.QtCore.QRect(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module PyQt5.QtCore , or try the search function .

Example 1
Project: screenshot   Author: SeptemberHX   File: screenshot.py    License: GNU General Public License v3.0 7 votes vote down vote up
def saveScreenshot(self, clipboard=False, fileName='screenshot.png', picType='png'):
        fullWindow = QRect(0, 0, self.width() - 1, self.height() - 1)
        selected = QRect(self.selected_area)
        if selected.left() < 0:
            selected.setLeft(0)
        if selected.right() >= self.width():
            selected.setRight(self.width() - 1)
        if selected.top() < 0:
            selected.setTop(0)
        if selected.bottom() >= self.height():
            selected.setBottom(self.height() - 1)

        source = (fullWindow & selected)
        source.setTopLeft(QPoint(source.topLeft().x() * self.scale, source.topLeft().y() * self.scale))
        source.setBottomRight(QPoint(source.bottomRight().x() * self.scale, source.bottomRight().y() * self.scale))
        image = self.screenPixel.copy(source)

        if clipboard:
            QGuiApplication.clipboard().setImage(QImage(image), QClipboard.Clipboard)
        else:
            image.save(fileName, picType, 10)
        self.target_img = image
        self.screen_shot_grabed.emit(QImage(image)) 
Example 2
Project: screenshot   Author: SeptemberHX   File: screenshot.py    License: GNU General Public License v3.0 7 votes vote down vote up
def drawSizeInfo(self):
        sizeInfoAreaWidth = 200
        sizeInfoAreaHeight = 30
        spacing = 5
        rect = self.selected_area.normalized()
        sizeInfoArea = QRect(rect.left(), rect.top() - spacing - sizeInfoAreaHeight,
                             sizeInfoAreaWidth, sizeInfoAreaHeight)

        if sizeInfoArea.top() < 0:
            sizeInfoArea.moveTopLeft(rect.topLeft() + QPoint(spacing, spacing))
        if sizeInfoArea.right() >= self.screenPixel.width():
            sizeInfoArea.moveTopLeft(rect.topLeft() - QPoint(spacing, spacing) - QPoint(sizeInfoAreaWidth, 0))
        if sizeInfoArea.left() < spacing:
            sizeInfoArea.moveLeft(spacing)
        if sizeInfoArea.top() < spacing:
            sizeInfoArea.moveTop(spacing)

        self.items_to_remove.append(self.graphics_scene.addRect(QRectF(sizeInfoArea), Qt.white, QBrush(Qt.black)))

        sizeInfo = self.graphics_scene.addSimpleText(
            '  {0} x {1}'.format(rect.width() * self.scale, rect.height() * self.scale))
        sizeInfo.setPos(sizeInfoArea.topLeft() + QPoint(0, 2))
        sizeInfo.setPen(QPen(QColor(255, 255, 255), 2))
        self.items_to_remove.append(sizeInfo) 
Example 3
Project: pkmeter   Author: pkkid   File: pkcharts.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def paintEvent(self, event):
        QtWidgets.QFrame.paintEvent(self, event)
        painter = QtGui.QPainter()
        painter.begin(self)
        painter.setRenderHint(QtGui.QPainter.Antialiasing)
        painter.setPen(Qt.NoPen)
        # Draw the Pie
        rwidth = int(min([self.width(), self.height()]) - 2)
        x = int((self.width() / 2) - (rwidth / 2))
        y = int((self.height() / 2) - (rwidth / 2))
        rect = QtCore.QRect(x, y, rwidth, rwidth)
        angle1 = 0
        for i in range(len(self.data)):
            angle2 = angle1 + (3.6 * self.data[i])
            painter.setBrush(QtGui.QBrush(self.colors[i % len(self.colors)]))
            painter.drawPie(rect, angle1*-16, (angle2-angle1)*-16)
            angle1 = angle2
        # Draw the remainer (background)
        angle2 = 360
        painter.setBrush(QtGui.QBrush(self.bgcolor))
        painter.drawPie(rect, angle1*-16, (angle2-angle1)*-16)
        painter.end() 
Example 4
Project: qutebrowser   Author: qutebrowser   File: test_webkitelem.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_iframe(self, stubs, js_rect):
        """Test an element in an iframe.

             0, 0                         200, 0
              ##############################
              #                            #
         0,10 # iframe  100,10             #
              #**********                  #
              #*        *                  #
              #*        *                  #
              #* e      * elem: 20,90 in iframe
              #**********                  #
        0,100 #                            #
              ##############################
            200, 0                         200, 200
        """
        frame = stubs.FakeWebFrame(QRect(0, 0, 200, 200))
        iframe = stubs.FakeWebFrame(QRect(0, 10, 100, 100), parent=frame)
        assert frame.geometry().contains(iframe.geometry())
        elem = get_webelem(QRect(20, 90, 10, 10), iframe,
                           js_rect_return=js_rect)
        assert elem.rect_on_view() == QRect(20, 10 + 90, 10, 10) 
Example 5
Project: Python-GUI   Author: arpitj07   File: scorewidnow.py    License: MIT License 6 votes vote down vote up
def setupUi(self, ScoreWindow):
        ScoreWindow.setObjectName("ScoreWindow")
        ScoreWindow.resize(471, 386)
        self.centralwidget = QtWidgets.QWidget(ScoreWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.Score = QtWidgets.QLineEdit(self.centralwidget)
        self.Score.setGeometry(QtCore.QRect(180, 180, 113, 22))
        self.Score.setObjectName("Score")
        self.teamscore = QtWidgets.QLabel(self.centralwidget)
        self.teamscore.setGeometry(QtCore.QRect(180, 130, 151, 20))
        font = QtGui.QFont()
        font.setBold(True)
        font.setWeight(75)
        self.teamscore.setFont(font)
        self.teamscore.setObjectName("teamscore")
        ScoreWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(ScoreWindow)
        self.statusbar.setObjectName("statusbar")
        ScoreWindow.setStatusBar(self.statusbar)

        self.retranslateUi(ScoreWindow)
        QtCore.QMetaObject.connectSlotsByName(ScoreWindow) 
Example 6
Project: qhangups   Author: xmikos   File: ui_qhangupsconversationslist.py    License: GNU General Public License v3.0 6 votes vote down vote up
def setupUi(self, QHangupsConversationsList):
        QHangupsConversationsList.setObjectName("QHangupsConversationsList")
        QHangupsConversationsList.resize(250, 500)
        self.centralwidget = QtWidgets.QWidget(QHangupsConversationsList)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setObjectName("verticalLayout")
        self.conversationsListWidget = QtWidgets.QListWidget(self.centralwidget)
        self.conversationsListWidget.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.conversationsListWidget.setObjectName("conversationsListWidget")
        self.verticalLayout.addWidget(self.conversationsListWidget)
        QHangupsConversationsList.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(QHangupsConversationsList)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 250, 27))
        self.menubar.setObjectName("menubar")
        QHangupsConversationsList.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(QHangupsConversationsList)
        self.statusbar.setObjectName("statusbar")
        QHangupsConversationsList.setStatusBar(self.statusbar)

        self.retranslateUi(QHangupsConversationsList)
        QtCore.QMetaObject.connectSlotsByName(QHangupsConversationsList) 
Example 7
Project: qhangups   Author: xmikos   File: ui_qhangupsconversations.py    License: GNU General Public License v3.0 6 votes vote down vote up
def setupUi(self, QHangupsConversations):
        QHangupsConversations.setObjectName("QHangupsConversations")
        QHangupsConversations.resize(500, 350)
        self.centralwidget = QtWidgets.QWidget(QHangupsConversations)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.conversationsTabWidget = QtWidgets.QTabWidget(self.centralwidget)
        self.conversationsTabWidget.setElideMode(QtCore.Qt.ElideRight)
        self.conversationsTabWidget.setTabsClosable(True)
        self.conversationsTabWidget.setMovable(True)
        self.conversationsTabWidget.setObjectName("conversationsTabWidget")
        self.gridLayout.addWidget(self.conversationsTabWidget, 0, 0, 1, 1)
        QHangupsConversations.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(QHangupsConversations)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 500, 27))
        self.menubar.setObjectName("menubar")
        QHangupsConversations.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(QHangupsConversations)
        self.statusbar.setObjectName("statusbar")
        QHangupsConversations.setStatusBar(self.statusbar)

        self.retranslateUi(QHangupsConversations)
        self.conversationsTabWidget.setCurrentIndex(-1)
        QtCore.QMetaObject.connectSlotsByName(QHangupsConversations) 
Example 8
Project: phidl   Author: amccaugh   File: quickplotter.py    License: MIT License 6 votes vote down vote up
def mousePressEvent(self, event):
        super(QGraphicsView, self).mousePressEvent(event)
        #==============================================================================
        #  Zoom to rectangle, from
        #  https://wiki.python.org/moin/PyQt/Selecting%20a%20region%20of%20a%20widget
        #==============================================================================
        if event.button() == Qt.RightButton:
            self._mousePressed = Qt.RightButton
            self._rb_origin = QPoint(event.pos())
            self.rubberBand.setGeometry(QRect(self._rb_origin, QSize()))
            self.rubberBand.show()
         #==============================================================================
        # Mouse panning, taken from
        # http://stackoverflow.com/a/15043279
        #==============================================================================
        elif event.button() == Qt.MidButton:
            self._mousePressed = Qt.MidButton
            self._mousePressedPos = event.pos()
            self.setCursor(QtCore.Qt.ClosedHandCursor)
            self._dragPos = event.pos() 
Example 9
Project: phidl   Author: amccaugh   File: quickplotter.py    License: MIT License 6 votes vote down vote up
def mouseMoveEvent(self, event):
        super(QGraphicsView, self).mouseMoveEvent(event)

        # # Useful debug
        # try:
        #     self.debug_label.setText(str(itemsBoundingRect_nogrid().width()))
        # except:
        #     print('Debug statement failed')

        # Update the X,Y label indicating where the mouse is on the geometry
        mouse_position = self.mapToScene(event.pos())
        self.mouse_position = [mouse_position.x(), mouse_position.y()]
        self.update_mouse_position_label()

        if not self._rb_origin.isNull() and self._mousePressed == Qt.RightButton:
            self.rubberBand.setGeometry(QRect(self._rb_origin, event.pos()).normalized())

        # Middle-click-to-pan
        if self._mousePressed == Qt.MidButton:
            newPos = event.pos()
            diff = newPos - self._dragPos
            self._dragPos = newPos
            self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() - diff.x())
            self.verticalScrollBar().setValue(self.verticalScrollBar().value() - diff.y())
#            event.accept() 
Example 10
Project: phidl   Author: amccaugh   File: quickplotter.py    License: MIT License 6 votes vote down vote up
def mouseReleaseEvent(self, event):
        if event.button() == Qt.RightButton:
            self.rubberBand.hide()
            rb_rect = QRect(self._rb_origin, event.pos())
            rb_center = rb_rect.center()
            rb_size = rb_rect.size()

            if abs(rb_size.width()) > 3 and abs(rb_size.height()) > 3:
                viewport_size = self.viewport().geometry().size()

                zoom_factor_x = abs(viewport_size.width() / rb_size.width())
                zoom_factor_y = abs(viewport_size.height() / rb_size.height())

                new_center = self.mapToScene(rb_center)

                zoom_factor = min(zoom_factor_x, zoom_factor_y)
                self.zoom_view(zoom_factor)
                self.centerOn(new_center)

            self.update_grid()

        if event.button() == Qt.MidButton:
            self.setCursor(Qt.ArrowCursor)
            self._mousePressed = None
            self.update_grid() 
Example 11
Project: MusicBox   Author: HuberTRoy   File: player.py    License: MIT License 6 votes vote down vote up
def getDetailInfo(self):
        """点击后进行动画效果的: 显示某歌曲的详细信息。"""
        self.shortInfo.hide()
        self.detailInfo.show()

        self.showDetail = QPropertyAnimation(self, b"geometry")

        x = self.pos().x()
        y = self.pos().y()

        self.showDetail.setStartValue(QRect(x, y, self.width(), self.height()))
        # 获取顶层父窗口的长度。
        self.showDetail.setEndValue(QRect(0, self.grandparent.header.height()+3, self.grandparent.width(), self.grandparent.mainContent.height()))
        self.showDetail.setDuration(300)
        self.showDetail.setEasingCurve(QEasingCurve.InBack)

        self.showDetail.start(QAbstractAnimation.DeleteWhenStopped)
        # 将该组件显示在最前,默认会嵌入到父组件里面。
        self.raise_()

        self.setDetailInfo() 
Example 12
Project: MusicBox   Author: HuberTRoy   File: player.py    License: MIT License 6 votes vote down vote up
def getShortInfo(self):
        """返回到原来的缩略图信息。"""
        self.detailInfo.hide()
        self.showShort = QPropertyAnimation(self, b"geometry")
        
        x = self.pos().x()
        y = self.pos().y()
        
        self.showShort.setStartValue(QRect(0, self.grandparent.header.height(), self.grandparent.width(), self.grandparent.mainContent.height()))
        self.showShort.setEndValue(QRect(0, self.grandparent.height()-64-self.parent.height(), self.grandparent.navigation.width(), 64))
        self.showShort.setDuration(300)
        self.showShort.setEasingCurve(QEasingCurve.InBack)
        
        self.showShort.start(QAbstractAnimation.DeleteWhenStopped)

        self.shortInfo.show()
        self.raise_() 
Example 13
Project: Cura   Author: Ultimaker   File: NetworkMJPGImage.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

        self._stream_buffer = QByteArray()
        self._stream_buffer_start_index = -1
        self._network_manager = None  # type: QNetworkAccessManager
        self._image_request = None  # type: QNetworkRequest
        self._image_reply = None  # type: QNetworkReply
        self._image = QImage()
        self._image_rect = QRect()

        self._source_url = QUrl()
        self._started = False

        self._mirror = False

        self.setAntialiasing(True) 
Example 14
Project: imperialism-remake   Author: Trilarion   File: qt.py    License: GNU General Public License v3.0 6 votes vote down vote up
def calculate_relative_position(parent_rect: QtCore.QRect, own_size: QtCore.QSize,
                                constraint: RelativeLayoutConstraint):
    """
    Calculates the position of the element, given its size, the position and size of the parent and a relative layout
    constraint. The position is the position of the parent plus the weighted size of the parent, the weighted size of
    the element and an offset. The weights and the offset are given by the constraint for each direction.

    :param parent_rect: parent coordinates and size as rectangle
    :param own_size: size of the element (width and height)
    :param constraint: relative layout constraint to apply
    :return: tuple of recommended x and y positions of the element
    """
    """
        Returns the left, upper corner of an object if the parent rectangle (QRect) is given and our own size (QSize)
        and a relative layout constraint (see RelativeLayoutConstraint).
    """
    x = (parent_rect.x()
         + constraint.x[0] * parent_rect.width()
         + constraint.x[1] * own_size.width()
         + constraint.x[2])
    y = (parent_rect.y()
         + constraint.y[0] * parent_rect.height()
         + constraint.y[1] * own_size.height()
         + constraint.y[2])
    return x, y 
Example 15
Project: imperialism-remake   Author: Trilarion   File: qt.py    License: GNU General Public License v3.0 6 votes vote down vote up
def setGeometry(self, rect: QtCore.QRect):  # noqa: N802
        """
        Layout the elements by calculating their relative position inside the parent, given the parents coordinates
        and the sizes of the elements. The width and height are not changed but the offset is computed according to
        the layout constraint and the parent size.

        :param rect: Position and size of the parent.
        """
        for item in self.items:
            o_size = item.widget().size()

            c = item.widget().layout_constraint

            x, y = calculate_relative_position(rect, o_size, c)

            item.setGeometry(QtCore.QRect(x, y, o_size.width(), o_size.height())) 
Example 16
Project: imperialism-remake   Author: Trilarion   File: test_lib_qt_graphics.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_calculate_constraints(self):

        parent = QtCore.QRect(10, 10, 1000, 500)
        size = QtCore.QSize(200, 100)

        constraint = qt.RelativeLayoutConstraint().south(10).west(20)
        x,y = qt.calculate_relative_position(parent, size, constraint)
        self.assertEqual((x,y), (30, 400))

        constraint = qt.RelativeLayoutConstraint().north(30).east(40)
        x, y = qt.calculate_relative_position(parent, size, constraint)
        self.assertEqual((x, y), (770, 40))

        constraint = qt.RelativeLayoutConstraint().center_horizontal().center_vertical()
        x1, y1 = qt.calculate_relative_position(parent, size, constraint)
        self.assertEqual((x1, y1), (410, 210)) 
Example 17
Project: stytra   Author: portugueslab   File: visual.py    License: GNU General Public License v3.0 6 votes vote down vote up
def paint(self, p, w, h):
        super().paint(p, w, h)

        if self._experiment.calibrator is not None:
            mm_px = self._experiment.calibrator.mm_px
        else:
            mm_px = 1

        # draw the background
        p.setPen(Qt.NoPen)
        p.setBrush(QBrush(QColor(*self.background_color)))
        self.clip(p, w, h)
        p.drawRect(QRect(-1, -1, w + 2, h + 2))

        # draw the circle
        p.setBrush(QBrush(QColor(*self.circle_color)))
        p.drawEllipse(QPointF(self.x * w, self.y * h), self.radius * w, self.radius * h) 
Example 18
Project: qutebrowser   Author: qutebrowser   File: test_webkitelem.py    License: GNU General Public License v3.0 5 votes vote down vote up
def frame(self, stubs):
        return stubs.FakeWebFrame(QRect(0, 0, 100, 100)) 
Example 19
Project: qutebrowser   Author: qutebrowser   File: test_webkitelem.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_invalid_frame_geometry(self, stubs):
        """Test with an invalid frame geometry."""
        rect = QRect(0, 0, 0, 0)
        assert not rect.isValid()
        frame = stubs.FakeWebFrame(rect)
        elem = get_webelem(QRect(0, 0, 10, 10), frame)
        assert not elem._is_visible(frame) 
Example 20
Project: qutebrowser   Author: qutebrowser   File: test_webkitelem.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_invalid_invisible(self, frame):
        """Test elements with an invalid geometry which are invisible."""
        elem = get_webelem(QRect(0, 0, 0, 0), frame)
        assert not elem.geometry().isValid()
        assert elem.geometry().x() == 0
        assert not elem._is_visible(frame) 
Example 21
Project: qutebrowser   Author: qutebrowser   File: test_webkitelem.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_invalid_visible(self, frame):
        """Test elements with an invalid geometry which are visible.

        This seems to happen sometimes in the real world, with real elements
        which *are* visible, but don't have a valid geometry.
        """
        elem = get_webelem(QRect(10, 10, 0, 0), frame)
        assert not elem.geometry().isValid()
        assert elem._is_visible(frame) 
Example 22
Project: qutebrowser   Author: qutebrowser   File: test_webkitelem.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_scrolled(self, geometry, visible, stubs):
        scrolled_frame = stubs.FakeWebFrame(QRect(0, 0, 100, 100),
                                            scroll=QPoint(10, 10))
        elem = get_webelem(geometry, scrolled_frame)
        assert elem._is_visible(scrolled_frame) == visible 
Example 23
Project: qutebrowser   Author: qutebrowser   File: test_webkitelem.py    License: GNU General Public License v3.0 5 votes vote down vote up
def objects(self, stubs):
        """Set up the following base situation.

             0, 0                         300, 0
              ##############################
              #                            #
         0,10 # iframe  100,10             #
              #**********                  #
              #*e       * elems[0]: 0, 0 in iframe (visible)
              #*        *                  #
              #* e      * elems[1]: 20,90 in iframe (visible)
              #**********                  #
        0,110 #.        .100,110           #
              #.        .                  #
              #. e      . elems[2]: 20,150 in iframe (not visible)
              #..........                  #
              #     e     elems[3]: 30, 180 in main frame (visible)
              #                            #
              #          frame             #
              ##############################
            300, 0                         300, 300

        Returns an Objects object with frame/iframe/elems attributes.
        """
        frame = stubs.FakeWebFrame(QRect(0, 0, 300, 300))
        iframe = stubs.FakeWebFrame(QRect(0, 10, 100, 100), parent=frame)
        assert frame.geometry().contains(iframe.geometry())
        elems = [
            get_webelem(QRect(0, 0, 10, 10), iframe),
            get_webelem(QRect(20, 90, 10, 10), iframe),
            get_webelem(QRect(20, 150, 10, 10), iframe),
            get_webelem(QRect(30, 180, 10, 10), frame),
        ]

        assert elems[0]._is_visible(frame)
        assert elems[1]._is_visible(frame)
        assert not elems[2]._is_visible(frame)
        assert elems[3]._is_visible(frame)

        return self.Objects(frame=frame, iframe=iframe, elems=elems) 
Example 24
Project: qutebrowser   Author: qutebrowser   File: test_webkitelem.py    License: GNU General Public License v3.0 5 votes vote down vote up
def invalid_objects(self, stubs):
        """Set up the following base situation.

             0, 0                         300, 0
              ##############################
              #                            #
         0,10 # iframe  100,10             #
              #**********                  #
              #* e      * elems[0]: 10, 10 in iframe (visible)
              #*        *                  #
              #*        *                  #
              #**********                  #
        0,110 #.        .100,110           #
              #.        .                  #
              #. e      . elems[2]: 20,150 in iframe (not visible)
              #..........                  #
              ##############################
            300, 0                         300, 300

        Returns an Objects object with frame/iframe/elems attributes.
        """
        frame = stubs.FakeWebFrame(QRect(0, 0, 300, 300))
        iframe = stubs.FakeWebFrame(QRect(0, 10, 100, 100), parent=frame)
        assert frame.geometry().contains(iframe.geometry())

        elems = [
            get_webelem(QRect(10, 10, 0, 0), iframe),
            get_webelem(QRect(20, 150, 0, 0), iframe),
        ]
        for e in elems:
            assert not e.geometry().isValid()

        return self.Objects(frame=frame, iframe=iframe, elems=elems) 
Example 25
Project: qutebrowser   Author: qutebrowser   File: test_webkitelem.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_simple(self, stubs, js_rect):
        geometry = QRect(5, 5, 4, 4)
        frame = stubs.FakeWebFrame(QRect(0, 0, 100, 100))
        elem = get_webelem(geometry, frame, js_rect_return=js_rect)
        assert elem.rect_on_view() == QRect(5, 5, 4, 4) 
Example 26
Project: qutebrowser   Author: qutebrowser   File: test_webkitelem.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_scrolled(self, stubs, js_rect):
        geometry = QRect(20, 20, 4, 4)
        frame = stubs.FakeWebFrame(QRect(0, 0, 100, 100),
                                   scroll=QPoint(10, 10))
        elem = get_webelem(geometry, frame, js_rect_return=js_rect)
        assert elem.rect_on_view() == QRect(20 - 10, 20 - 10, 4, 4) 
Example 27
Project: qutebrowser   Author: qutebrowser   File: test_webkitelem.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_zoomed(self, stubs, config_stub, js_rect, monkeypatch,
                    zoom_text_only):
        """Make sure the coordinates are adjusted when zoomed."""
        monkeypatch.setattr(objects, 'backend', usertypes.Backend.QtWebKit)
        config_stub.val.zoom.text_only = zoom_text_only
        geometry = QRect(10, 10, 4, 4)
        frame = stubs.FakeWebFrame(QRect(0, 0, 100, 100), zoom=0.5)
        elem = get_webelem(geometry, frame, js_rect_return=js_rect,
                           zoom_text_only=zoom_text_only)
        assert elem.rect_on_view() == QRect(10, 10, 4, 4) 
Example 28
Project: qutebrowser   Author: qutebrowser   File: webkitelem.py    License: GNU General Public License v3.0 5 votes vote down vote up
def geometry(self) -> QRect:
        self._check_vanished()
        return self._elem.geometry() 
Example 29
Project: qutebrowser   Author: qutebrowser   File: webkitelem.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _rect_on_view_js(self) -> typing.Optional[QRect]:
        """Javascript implementation for rect_on_view."""
        # FIXME:qtwebengine maybe we can reuse this?
        rects = self._elem.evaluateJavaScript("this.getClientRects()")
        if rects is None:  # pragma: no cover
            # On e.g. Void Linux with musl libc, the stack size is too small
            # for jsc, and running JS will fail. If that happens, fall back to
            # the Python implementation.
            # https://github.com/qutebrowser/qutebrowser/issues/1641
            return None

        text = utils.compact_text(self._elem.toOuterXml(), 500)
        log.webelem.vdebug(  # type: ignore[attr-defined]
            "Client rectangles of element '{}': {}".format(text, rects))

        for i in range(int(rects.get("length", 0))):
            rect = rects[str(i)]
            width = rect.get("width", 0)
            height = rect.get("height", 0)
            if width > 1 and height > 1:
                # fix coordinates according to zoom level
                zoom = self._elem.webFrame().zoomFactor()
                if not config.val.zoom.text_only:
                    rect["left"] *= zoom
                    rect["top"] *= zoom
                    width *= zoom
                    height *= zoom
                rect = QRect(int(rect["left"]), int(rect["top"]),
                             int(width), int(height))
                frame = self._elem.webFrame()
                while frame is not None:
                    # Translate to parent frames' position (scroll position
                    # is taken care of inside getClientRects)
                    rect.translate(frame.geometry().topLeft())
                    frame = frame.parentFrame()
                return rect

        return None 
Example 30
Project: qutebrowser   Author: qutebrowser   File: webkitelem.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _rect_on_view_python(self,
                             elem_geometry: typing.Optional[QRect]) -> QRect:
        """Python implementation for rect_on_view."""
        if elem_geometry is None:
            geometry = self._elem.geometry()
        else:
            geometry = elem_geometry
        frame = self._elem.webFrame()
        rect = QRect(geometry)
        while frame is not None:
            rect.translate(frame.geometry().topLeft())
            rect.translate(frame.scrollPosition() * -1)
            frame = frame.parentFrame()
        return rect