Python PyQt5.QtGui.QTransform() Examples

The following are 25 code examples for showing how to use PyQt5.QtGui.QTransform(). 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 want to check out the right sidebar which shows the related API usage.

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

Example 1
Project: lector   Author: zdenop   File: ocrwidget.py    License: GNU General Public License v2.0 7 votes vote down vote up
def prepareDimensions(self):
        #set scene size and view scale
        scene = self.scene()
        scene.setSize()

        vw = float(self.width())
        vh = float(self.height())
        iw = float(scene.im.size[0])
        ih = float(scene.im.size[1])
        ratio = min(vw/iw, vh/ih)
        # TODO: check this - there was QMatrix
        # self.setMatrix(QTransform(.95*ratio, 0., 0., .95*ratio, 0., 0.))

        OcrArea.resizeBorder = 5 / ratio
        self.areaBorder = 2 / ratio
        self.areaTextSize = 10 / ratio

        #show image
        scene.generateQtImage()
        self.resetCachedContent()
        scene.isModified = False 
Example 2
Project: CodeAtlasSublime   Author: league1991   File: codeview.py    License: Eclipse Public License 1.0 6 votes vote down vote up
def drawForeground(self, painter, rectF):
		super(CodeView, self).drawForeground(painter, rectF)

		if self.isFrameSelectMode:
			if self.mousePressPnt and self.mouseCurPnt:
				topLeftX = min(self.mousePressPnt.x(), self.mouseCurPnt.x())
				topLeftY = min(self.mousePressPnt.y(), self.mouseCurPnt.y())
				width = abs(self.mousePressPnt.x()-self.mouseCurPnt.x())
				height= abs(self.mousePressPnt.y()-self.mouseCurPnt.y())

				painter.setPen(QtGui.QPen(QtGui.QColor(100,164,230),1.0))
				painter.setBrush(QtGui.QBrush(QtGui.QColor(100,164,230,100)))
				painter.setTransform(QtGui.QTransform())
				painter.drawRect(topLeftX, topLeftY, width, height)
		self.drawScheme(painter, rectF)
		self.drawLegend(painter, rectF) 
Example 3
Project: Computer-graphics   Author: Panda-Lewandowski   File: lab7.py    License: MIT License 5 votes vote down vote up
def mouseMoveEvent(self, event):
        global now, w
        if w.input_rect:
            if now is None:
                now = event.scenePos()
            else:
                self.removeItem(self.itemAt(now, QTransform()))
                p = event.scenePos()
                self.addRect(now.x(), now.y(), abs(now.x() - p.x()), abs(now.y() - p.y())) 
Example 4
Project: Computer-graphics   Author: Panda-Lewandowski   File: lab7.py    License: MIT License 5 votes vote down vote up
def clipping(win):
    buf = win.scene.itemAt(now, QTransform()).rect()
    win.clip = [buf.left(), buf.right(), buf.top(),  buf.bottom()]
    for b in win.lines:
        pass
        win.pen.setColor(blue)
        cohen_sutherland(b, win.clip, win)
        win.pen.setColor(red) 
Example 5
Project: imperialism-remake   Author: Trilarion   File: landUnitType.py    License: GNU General Public License v3.0 5 votes vote down vote up
def mirror_pixmap(pixmap):
    transform = QTransform()
    transform.scale(-1, 1)
    return QPixmap(pixmap.transformed(transform)) 
Example 6
Project: PyPipboyApp   Author: matzman666   File: globalmapwidget.py    License: GNU General Public License v3.0 5 votes vote down vote up
def setZoomLevel(self, zoom, mapposx, mapposy):
        self.mapItem.setTransform(QtGui.QTransform.fromScale(zoom, zoom))
        self.gwidget.mapScene.setSceneRect(self.mapItem.sceneBoundingRect())
        if mapposx >= 0 and mapposy >=0:
            self.gwidget.mapView.centerOn(mapposx * zoom, mapposy * zoom) 
Example 7
Project: stytra   Author: portugueslab   File: visual.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_transform(self, w, h, x, y):
        return QTransform().rotate(self.theta * 180 / np.pi).translate(x, y) 
Example 8
Project: stytra   Author: portugueslab   File: visual.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_tile_ranges(self, imw, imh, w, h, tr: QTransform):
        """ Calculates the number of tiles depending on the transform.

        Parameters
        ----------
        imw
        imh
        w
        h
        tr

        Returns
        -------

        """

        # we find where the display surface is in the coordinate system of a single tile
        corner_points = [
            np.array([0.0, 0.0]),
            np.array([w, 0.0]),
            np.array([w, h]),
            np.array([0.0, h]),
        ]
        points_transformed = np.array(
            [tr.inverted()[0].map(*cp) for cp in corner_points]
        )

        # calculate the rectangle covering the transformed display surface
        min_x, min_y = np.min(points_transformed, 0)
        max_x, max_y = np.max(points_transformed, 0)

        # count which tiles need to be drawn
        x_start, x_end = (int(np.floor(min_x / imw)), int(np.ceil(max_x / imw)))
        y_start, y_end = (int(np.floor(min_y / imh)), int(np.ceil(max_y / imh)))

        return range(x_start, x_end + 1), range(y_start, y_end + 1) 
Example 9
Project: stytra   Author: portugueslab   File: visual.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_transform(self, w, h, x, y):
        return (
            QTransform().translate(-w / 2, -h / 2)
            * super().get_transform(w, h, x, y)
            * QTransform().translate(w / 2, h / 2)
        ) 
Example 10
Project: pychemqt   Author: jjgomera   File: flujo.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, text, parent=None, position=QtCore.QPointF(0, 0), transform=QtGui.QTransform(), selectable=True):
        super(TextItem, self).__init__(parent=parent)
        if selectable:
            self.setFlags(QtWidgets.QGraphicsItem.ItemIsSelectable | QtWidgets.QGraphicsItem.ItemIsMovable |
                          QtWidgets.QGraphicsItem.ItemSendsGeometryChanges | QtWidgets.QGraphicsItem.ItemIsFocusable)
        else:
            self.setFlags(QtWidgets.QGraphicsItem.ItemIsMovable)
        self.setHtml(text)
        self.setPos(position)
        self.setTransform(transform)
        self.selectable = selectable 
Example 11
Project: pychemqt   Author: jjgomera   File: flujo.py    License: GNU General Public License v3.0 5 votes vote down vote up
def readItemFromStream(self, stream):
        type = QtCore.QString()
        matrix = QtGui.QTransform()
        stream >> type >> matrix
        if type == "txt":
            text = QtCore.QString()
            stream >> text
            item = TextItem(text)
        elif type == "square":
            rect = QtCore.QRectF()
            pen = QtGui.QPen()
            stream >> rect >> pen
            item = RectItem()
            item.setRect(rect)
            item.setPen(pen)
        elif type == "ellipse":
            rect = QtCore.QRectF()
            pen = QtGui.QPen()
            stream >> rect >> pen
            item = EllipseItem()
            item.setRect(rect)
            item.setPen(pen)
        elif type == "equip":
            name = QtCore.QString()
            stream >> name
            dialogoid = stream.readInt32()
            item = EquipmentItem(name, dialogoid)

        item.setTransform(matrix)
        return item 
Example 12
Project: vidcutter   Author: ozmartian   File: graphicseffects.py    License: GNU General Public License v3.0 5 votes vote down vote up
def draw(self, painter: QPainter) -> None:
        if self.sourceIsPixmap():
            pixmap, offset = self.sourcePixmap(Qt.LogicalCoordinates, QGraphicsEffect.PadToEffectiveBoundingRect)
        else:
            pixmap, offset = self.sourcePixmap(Qt.DeviceCoordinates, QGraphicsEffect.PadToEffectiveBoundingRect)
            painter.setWorldTransform(QTransform())
        painter.setBrush(Qt.black)
        painter.drawRect(pixmap.rect())
        painter.setOpacity(self.opacity)
        painter.drawPixmap(offset, pixmap) 
Example 13
Project: CvStudio   Author: haruiz   File: image_graphics_view.py    License: MIT License 5 votes vote down vote up
def fit_to_window(self):
        if not self._pixmap or not self._pixmap.pixmap():
            return
        self.resetTransform()
        self.setTransform(QtGui.QTransform())
        self.fitInView(self._pixmap, QtCore.Qt.KeepAspectRatio) 
Example 14
Project: ezdxf   Author: mozman   File: cad_viewer.py    License: MIT License 5 votes vote down vote up
def mouseMoveEvent(self, event: qg.QMouseEvent) -> None:
        pos = self.mapToScene(event.pos())
        self._current_item = self.scene().itemAt(pos, qg.QTransform())
        self.element_selected.emit(self._current_item, pos)
        self.scene().invalidate(self.sceneRect(), qw.QGraphicsScene.ForegroundLayer)
        super().mouseMoveEvent(event) 
Example 15
Project: ezdxf   Author: mozman   File: pyqt_backend.py    License: MIT License 5 votes vote down vote up
def _get_x_scale(t: qg.QTransform) -> float:
    return math.sqrt(t.m11() * t.m11() + t.m21() * t.m21()) 
Example 16
Project: ezdxf   Author: mozman   File: pyqt_backend.py    License: MIT License 5 votes vote down vote up
def _matrix_to_qtransform(matrix: Matrix44) -> qg.QTransform:
    """ Qt also uses row-vectors so the translation elements are placed in the bottom row

    This is only a simple conversion which assumes that although the transformation is 4x4,
    it does not involve the z axis.

    A more correct transformation could be implemented like so:
    https://stackoverflow.com/questions/10629737/convert-3d-4x4-rotation-matrix-into-2d
    """
    return qg.QTransform(*matrix.get_2d_transformation()) 
Example 17
Project: Mastering-GUI-Programming-with-Python   Author: PacktPublishing   File: tankity_tank_tank_tank.py    License: MIT License 5 votes vote down vote up
def __init__(self, color, y_pos, side=TOP):
        super().__init__()
        self.side = side
        # Define the tank's lookp
        self.bitmap = qtg.QBitmap.fromData(qtc.QSize(8, 8), self.TANK_BM)
        transform = qtg.QTransform()
        transform.scale(4, 4)  # scale to 32x32
        if self.side == self.TOP:  # We're pointing down
            transform.rotate(180)
        self.bitmap = self.bitmap.transformed(transform)
        self.pen = qtg.QPen(qtg.QColor(color))

        # Define the tank's position
        if self.side == self.BOTTOM:
            y_pos -= self.bitmap.height()
        self.setPos(0, y_pos)

        # Move the tank
        self.animation = qtc.QPropertyAnimation(self, b'x')
        self.animation.setStartValue(0)
        self.animation.setEndValue(SCREEN_WIDTH - self.bitmap.width())
        self.animation.setDuration(2000)
        self.animation.finished.connect(self.toggle_direction)
        if self.side == self.TOP:
            self.toggle_direction()
        self.animation.start()

        # create a bullet
        bullet_y = (
            y_pos - self.bitmap.height()
            if self.side == self.BOTTOM
            else y_pos + self.bitmap.height()
        )
        self.bullet = Bullet(bullet_y, self.side == self.BOTTOM) 
Example 18
Project: urh   Author: jopohl   File: SendRecvDialog.py    License: GNU General Public License v3.0 5 votes vote down vote up
def on_slider_y_scale_value_changed(self, new_value: int):
        # Scale Up = Top Half, Scale Down = Lower Half
        transform = self.graphics_view.transform()
        self.graphics_view.setTransform(QTransform(transform.m11(), transform.m12(), transform.m13(),
                                                   transform.m21(), new_value, transform.m23(),
                                                   transform.m31(), transform.m32(), transform.m33())) 
Example 19
Project: urh   Author: jopohl   File: Selection.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _get_selected_edge(self, pos: QPointF, transform: QTransform, horizontal_selection: bool):
        x1, x2 = self.x, self.x + self.width
        y1, y2 = self.y, self.y + self.height
        x, y = pos.x(), pos.y()

        spacing = 5
        spacing /= transform.m11() if horizontal_selection else transform.m22()

        if horizontal_selection:
            x1a, x1b = x1 - spacing, x1 + spacing
            y1a, y1b = y1, y2
            x2a, x2b = x2 - spacing, x2 + spacing
            y2a, y2b = y1, y2
        else:
            x1a, x1b, x2a, x2b = x1, x2, x1, x2
            y1a, y1b = min(y1 - spacing, y1 + spacing), max(y1 - spacing, y1 + spacing)
            y2a, y2b = min(y2 - spacing, y2 + spacing), max(y2 - spacing, y2 + spacing)

        if x1a < x < x1b and y1a < y < y1b:
            self.selected_edge = 0
            return 0

        if x2a < x < x2b and y2a < y < y2b:
            self.selected_edge = 1
            return 1

        self.selected_edge = None
        return None 
Example 20
Project: urh   Author: jopohl   File: VerticalSelection.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_selected_edge(self, pos: QPointF, transform: QTransform):
        return super()._get_selected_edge(pos, transform, horizontal_selection=False) 
Example 21
Project: urh   Author: jopohl   File: HorizontalSelection.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_selected_edge(self, pos: QPointF, transform: QTransform):
        return super()._get_selected_edge(pos, transform, horizontal_selection=True) 
Example 22
Project: CodeAtlasSublime   Author: league1991   File: codeview.py    License: Eclipse Public License 1.0 5 votes vote down vote up
def drawScheme(self, painter, rectF):
		from UIManager import UIManager
		scene = UIManager.instance().getScene()
		schemeList = scene.getCurrentSchemeList()
		nScheme = len(schemeList)
		if not nScheme:
			return
		painter.setTransform(QtGui.QTransform())
		painter.setFont(self.hudFont)
		colorList = scene.getCurrentSchemeColorList()
		cw = 10
		y  = 10

		maxWidth = 0
		for ithScheme, schemeName in enumerate(schemeList):
			schemeSize = self.hudFontMetric.size(QtCore.Qt.TextSingleLine, schemeName)
			maxWidth = max(maxWidth, schemeSize.width())

		painter.setCompositionMode(QtGui.QPainter.CompositionMode_Multiply)
		painter.setPen(QtCore.Qt.NoPen)
		painter.setBrush(QtGui.QColor(0,0,0,150))
		painter.drawRect(5,5, 80 + maxWidth, nScheme * cw + (nScheme-1)*2 + 10)

		painter.setCompositionMode(QtGui.QPainter.CompositionMode_Source)
		for ithScheme, schemeName in enumerate(schemeList):
			painter.setPen(QtCore.Qt.NoPen)
			painter.setBrush(QtGui.QBrush(colorList[ithScheme]))
			painter.drawRect(QtCore.QRect(10,y+5,20,2))

			painter.setPen(QtGui.QPen(QtGui.QColor(255,157,38,255),1))
			painter.drawText(39, y+cw, 'Alt + %s' % (ithScheme+1,))
			painter.setPen(QtGui.QPen(QtGui.QColor(255,255,255,255),1))
			painter.drawText(QtCore.QRect(80,y-1,maxWidth,cw+3), QtCore.Qt.AlignRight | QtCore.Qt.AlignTop, schemeName)
			y += cw + 2 
Example 23
Project: CodeAtlasSublime   Author: league1991   File: codeview.py    License: Eclipse Public License 1.0 5 votes vote down vote up
def drawLegend(self, painter, rectF):
		painter.setTransform(QtGui.QTransform())
		painter.setFont(self.hudFont)

		from UIManager import UIManager
		scene = UIManager.instance().getScene()
		itemDict = scene.getItemDict()
		classNameDict = {}
		for uname, item in itemDict.items():
			if item.isSelected() or item.isConnectedToFocusNode:
				cname = item.getClassName()
				if not cname:
					cname = '[global function]'
				classNameDict[cname] = item.getColor()

		maxWidth = 0
		cw = 10
		nClasses = len(classNameDict)
		if not nClasses:
			return

		for className in classNameDict.keys():
			classSize = self.hudFontMetric.size(QtCore.Qt.TextSingleLine, className)
			maxWidth = max(maxWidth, classSize.width())

		painter.setCompositionMode(QtGui.QPainter.CompositionMode_Multiply)
		painter.setPen(QtCore.Qt.NoPen)
		painter.setBrush(QtGui.QColor(0,0,0,150))
		interiorHeight = nClasses * cw + (nClasses-1)*2
		painter.drawRect(5,self.height()-15-interiorHeight, 22 + maxWidth, interiorHeight + 10)

		painter.setCompositionMode(QtGui.QPainter.CompositionMode_Source)
		y = self.height() - 20
		for cname, clr in classNameDict.items():
			painter.setPen(QtCore.Qt.NoPen)
			painter.setBrush(QtGui.QBrush(clr))
			painter.drawRect(QtCore.QRect(10,y,cw,cw))

			painter.setPen(QtGui.QPen(QtGui.QColor(255,255,255,255),1))
			painter.drawText(cw+12, y+cw, cname)
			y -= cw + 2 
Example 24
Project: Computer-graphics   Author: Panda-Lewandowski   File: lab7.py    License: MIT License 4 votes vote down vote up
def add_bars(win):
    global now
    if now is None:
        QMessageBox.warning(win, "Внимание!", "Не введен отсекатель!")
        return
    buf = win.scene.itemAt(now, QTransform())
    if buf is None:
        QMessageBox.warning(win, "Внимание!", "Не введен отсекатель!")
    else:
        buf = buf.rect()
        win.clip = [buf.left(), buf.right(), buf.top(),  buf.bottom()]

        t = abs(win.clip[2] - win.clip[3]) * 0.8
        k = abs(win.clip[0] - win.clip[1]) * 0.8
        # задаем граничные отрезки
        win.pen.setColor(red)
        w.lines.append([[win.clip[0], win.clip[2] + t],  [win.clip[0], win.clip[3] - t]])
        add_row(w)
        i = w.table.rowCount() - 1
        item_b = QTableWidgetItem("[{0}, {1}]".format(win.clip[0], win.clip[2] + t))
        item_e = QTableWidgetItem("[{0}, {1}]".format(win.clip[0], win.clip[3] - t))
        w.table.setItem(i, 0, item_b)
        w.table.setItem(i, 1, item_e)
        win.scene.addLine(win.clip[0], win.clip[2] + t,  win.clip[0], win.clip[3] - t, win.pen)

        w.lines.append([[win.clip[1], win.clip[2] + t],  [win.clip[1], win.clip[3] - t]])
        add_row(w)
        i = w.table.rowCount() - 1
        item_b = QTableWidgetItem("[{0}, {1}]".format(win.clip[1], win.clip[2] + t))
        item_e = QTableWidgetItem("[{0}, {1}]".format(win.clip[1], win.clip[3] - t))
        w.table.setItem(i, 0, item_b)
        w.table.setItem(i, 1, item_e)
        win.scene.addLine(win.clip[1], win.clip[3] - t,  win.clip[1], win.clip[2] + t, win.pen)

        w.lines.append([[win.clip[0] + k, win.clip[2]], [win.clip[1] - k, win.clip[2]]])
        add_row(w)
        i = w.table.rowCount() - 1
        item_b = QTableWidgetItem("[{0}, {1}]".format(win.clip[0] + k, win.clip[2]))
        item_e = QTableWidgetItem("[{0}, {1}]".format(win.clip[1] - k, win.clip[2]))
        w.table.setItem(i, 0, item_b)
        w.table.setItem(i, 1, item_e)
        win.scene.addLine(win.clip[0] + k, win.clip[2], win.clip[1] - k, win.clip[2], win.pen)

        w.lines.append([[win.clip[0] + k, win.clip[3]], [win.clip[1] - k, win.clip[3]]])
        add_row(w)
        i = w.table.rowCount() - 1
        item_b = QTableWidgetItem("[{0}, {1}]".format(win.clip[0] + k, win.clip[3]))
        item_e = QTableWidgetItem("[{0}, {1}]".format(win.clip[1] - k, win.clip[3]))
        w.table.setItem(i, 0, item_b)
        w.table.setItem(i, 1, item_e)
        win.scene.addLine(win.clip[0] + k, win.clip[3], win.clip[1] - k, win.clip[3], win.pen) 
Example 25
Project: PyQt   Author: PyQt5   File: FlipWidget.py    License: GNU General Public License v3.0 4 votes vote down vote up
def paintEvent(self, event):
        super(FlipWidget, self).paintEvent(event)

        if hasattr(self, 'image1') and hasattr(self, 'image2') and self.isVisible():

            painter = QPainter(self)
            painter.setRenderHint(QPainter.Antialiasing, True)
            painter.setRenderHint(QPainter.SmoothPixmapTransform, True)

            # 变换
            transform = QTransform()
            # 把圆心设置为矩形中心
            transform.translate(self.width() / 2, self.height() / 2)

            if self._angle >= -90 and self._angle <= 90:
                # 当翻转角度在90范围内显示第一张图,且从大图缩放到小图的过程
                painter.save()
                # 设置翻转角度
                transform.rotate(self._angle, Qt.YAxis)
                painter.setTransform(transform)
                # 缩放图片高度
                width = self.image1.width() / 2
                height = int(self.image1.height() *
                             (1 - abs(self._angle / self.Scale) / 100))
                image = self.image1.scaled(
                    self.image1.width(), height,
                    Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
                painter.drawPixmap(
                    QPointF(-width, -height / 2), image)
                painter.restore()
            else:
                # 当翻转角度在90范围内显示第二张图,且从小图缩放到原图的过程
                painter.save()
                if self._angle > 0:
                    angle = 180 + self._angle
                else:
                    angle = self._angle - 180
                # 设置翻转角度, 注意这里角度有差异
                transform.rotate(angle, Qt.YAxis)
                painter.setTransform(transform)
                # 缩放图片高度
                width = self.image2.width() / 2
                height = int(self.image2.height() *
                             (1 - ((360 - abs(angle)) / self.Scale / 100)))
                image = self.image2.scaled(
                    self.image2.width(), height,
                    Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
                painter.drawPixmap(
                    QPointF(-width, -height / 2), image)
                painter.restore()