当前位置: 首页>>代码示例>>Python>>正文


Python QTransform.translate方法代码示例

本文整理汇总了Python中PyQt5.QtGui.QTransform.translate方法的典型用法代码示例。如果您正苦于以下问题:Python QTransform.translate方法的具体用法?Python QTransform.translate怎么用?Python QTransform.translate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PyQt5.QtGui.QTransform的用法示例。


在下文中一共展示了QTransform.translate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: paintEvent

# 需要导入模块: from PyQt5.QtGui import QTransform [as 别名]
# 或者: from PyQt5.QtGui.QTransform import translate [as 别名]
    def paintEvent(self, event):
        """QToolBar.paintEvent reimplementation
        Draws buttons, dock icon and text
        """
        rect = self._spacer.rect()

        painter = QPainter(self)

        transform = QTransform()
        transform.translate(self._spacer.pos().x(), self._spacer.pos().y())
        painter.setTransform(transform)

        """ Not supported currently
        if  self._dock.features() & QDockWidget.DockWidgetVerticalTitleBar :
            transform = QTransform()

            rect.setSize(QSize(rect.height(), rect.width()))
            transform.rotate(-90)
            transform.translate(-rect.width(), 0)

            painter.setTransform(transform)
        """

        # icon / title
        optionB = QStyleOptionButton()
        optionB.initFrom(self._dock)
        optionB.rect = rect
        optionB.text = self._dock.windowTitle()
        optionB.iconSize = self.iconSize()
        optionB.icon = self._dock.windowIcon()

        self.style().drawControl(QStyle.CE_PushButtonLabel, optionB, painter, self._dock)
开发者ID:gpa14,项目名称:enki,代码行数:34,代码来源:dockwidget.py

示例2: setHeading

# 需要导入模块: from PyQt5.QtGui import QTransform [as 别名]
# 或者: from PyQt5.QtGui.QTransform import translate [as 别名]
 def setHeading(self, heading):
     xForm = QTransform()
     xForm.translate(self.__center_x, self.__center_y)
     xForm.rotate(math.degrees(heading))
     xForm.translate(-self.__center_x, -self.__center_y)
     self.setTransform(xForm)
     
     self.mapTextureBasedOnZoom(self.brush())
开发者ID:dtdavi1,项目名称:acs_dashboards,代码行数:10,代码来源:mapGraphicsIcon.py

示例3: mapTextureBasedOnZoom

# 需要导入模块: from PyQt5.QtGui import QTransform [as 别名]
# 或者: from PyQt5.QtGui.QTransform import translate [as 别名]
 def mapTextureBasedOnZoom(self, brush):
     if brush.texture().width() > 0 and brush.texture().height() > 0:
         brush_trans = QTransform()
         brush_trans.translate(self.__center_x - self.__width * 0.5,
                 self.__center_y - self.__height * 0.5)
         brush_trans.scale(self.__width/float(brush.texture().width()),
                 self.__height/float(brush.texture().height()))
         brush.setTransform(brush_trans)
 
     self.setBrush(brush)
开发者ID:dtdavi1,项目名称:acs_dashboards,代码行数:12,代码来源:mapGraphicsIcon.py

示例4: resizeEvent

# 需要导入模块: from PyQt5.QtGui import QTransform [as 别名]
# 或者: from PyQt5.QtGui.QTransform import translate [as 别名]
 def resizeEvent(self, event):
     self.setUpdatesEnabled(False)
     super().resizeEvent(event)
     # center scene in viewport
     r = self.rect()
     t = QTransform()
     t.translate(-r.width() / 2, -r.height() / 2)
     r = QRectF(QPointF(r.x(), r.y()) * t, QSizeF(r.width(), r.height()))
     self.setSceneRect(r)
     self.__resizeDelayTimer.start(self.resizeUpdateDelay)
     self.setUpdatesEnabled(True)
开发者ID:Manko10,项目名称:WekaVisualizer,代码行数:13,代码来源:StarPlot.py

示例5: transform

# 需要导入模块: from PyQt5.QtGui import QTransform [as 别名]
# 或者: from PyQt5.QtGui.QTransform import translate [as 别名]
 def transform(self):
     try:
         return self.__dict__['transform'] if self.scale else QTransform()
     except KeyError:
         transform = QTransform()
         image = self.client.image
         if image is not None and not image.isNull():
             scale = min(self.width()/image.width(), self.height()/image.height())
             transform.translate((self.width() - image.width()*scale)/2, (self.height() - image.height()*scale)/2)
             transform.scale(scale, scale)
             transform = self.__dict__.setdefault('transform', transform)
         return transform
开发者ID:AGProjects,项目名称:blink-qt,代码行数:14,代码来源:vncviewer.py

示例6: textureRect

# 需要导入模块: from PyQt5.QtGui import QTransform [as 别名]
# 或者: from PyQt5.QtGui.QTransform import translate [as 别名]
    def textureRect(self, rect_tile):
        tile_info = rect_tile.data(0)

        if tile_info is None:
            return False

        pm = QPixmap(self.__tiler.tile_to_path(tile_info))  
        if pm.width() != 256:
            #print("Probably didn't get tile:", next_tile_info.x, next_tile_info.y, "\n")
            #TODO: Attempt to texture with a lower res tile
            #Bear in mind that you will have to take Mercator projection into
            #account on the lower res tile.
            
            #First Attempt: didn't work
            #if tile_info.zoom <= self.__tiler.get_min_zoom():
            #    return False
            #
            #find colocated lower res tile
            #(lat,lon) = tile_info.coord()
            #tile_info2 = self.__tiler.coord_to_tile(lat,lon, tile_info.zoom-1)
            #rect_tile.setData(0, tile_info2)
            #print("prev tile: ", tile_info.tile, tile_info.coord())
            #return self.textureRect(rect_tile, depth + 1)

            #until such time as we can pull lower res tiles and figure out
            #which area to render on a rectangle, skip:
            return False

        topLeft = rect_tile.boundingRect().topLeft()
        bottomRight = rect_tile.boundingRect().bottomRight()   
       
        width = bottomRight.x() - topLeft.x()
        height = bottomRight.y() - topLeft.y()

        brush_trans = QTransform()        
        brush_trans.translate(topLeft.x(), topLeft.y())
        brush_trans.scale(width/256.0, height/256.0)

        qb = QBrush(pm)
        qb.setTransform(brush_trans)
        rect_tile.setBrush(qb)
   
        return True
开发者ID:dtdavi1,项目名称:acs_dashboards,代码行数:45,代码来源:mapWidgetWrapper.py

示例7: syncWithMapObject

# 需要导入模块: from PyQt5.QtGui import QTransform [as 别名]
# 或者: from PyQt5.QtGui.QTransform import translate [as 别名]
 def syncWithMapObject(self, renderer):
     nameVisible = self.mObject.isVisible() and self.mObject.name()!=''
     self.setVisible(nameVisible)
     if (not nameVisible):
         return
     metrics = QFontMetricsF(QGuiApplication.font())
     boundingRect = metrics.boundingRect(self.mObject.name())
     boundingRect.translate(-boundingRect.width() / 2, -labelDistance)
     boundingRect.adjust(-labelMargin*2, -labelMargin, labelMargin*2, labelMargin)
     pixelPos = renderer.pixelToScreenCoords_(self.mObject.position())
     bounds = objectBounds(self.mObject, renderer)
     # Adjust the bounding box for object rotation
     transform = QTransform()
     transform.translate(pixelPos.x(), pixelPos.y())
     transform.rotate(self.mObject.rotation())
     transform.translate(-pixelPos.x(), -pixelPos.y())
     bounds = transform.mapRect(bounds)
     # Center the object name on the object bounding box
     pos = QPointF((bounds.left() + bounds.right()) / 2, bounds.top())
     self.setPos(pos + self.mObject.objectGroup().offset())
     if (self.mBoundingRect != boundingRect):
         self.prepareGeometryChange()
         self.mBoundingRect = boundingRect
开发者ID:theall,项目名称:Python-Tiled,代码行数:25,代码来源:objectselectionitem.py

示例8: _createPreXoverPainterPath

# 需要导入模块: from PyQt5.QtGui import QTransform [as 别名]
# 或者: from PyQt5.QtGui.QTransform import translate [as 别名]
def _createPreXoverPainterPath( elements: List[List[QPointF]],
                                end_poly: QPolygonF = None,
                                is_fwd: bool = True) -> QPainterPath:
    path = QPainterPath()

    next_pt = None
    for element in elements:
        start_pt = element[0]
        path.moveTo(start_pt)
        for next_pt in element[1:]:
            path.lineTo(next_pt)

    if end_poly is not None:
        h = end_poly.boundingRect().height()/2
        xoffset = -h if is_fwd else h
        w = end_poly.boundingRect().width()
        yoffset = w if is_fwd else -w
        angle = -90 if is_fwd else 90
        T = QTransform()
        T.translate(next_pt.x()+xoffset, next_pt.y()+yoffset)
        T.rotate(angle)
        path.addPolygon(T.map(end_poly))
    return path
开发者ID:cadnano,项目名称:cadnano2.5,代码行数:25,代码来源:pathextras.py

示例9: paintEvent

# 需要导入模块: from PyQt5.QtGui import QTransform [as 别名]
# 或者: from PyQt5.QtGui.QTransform import translate [as 别名]
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.fillRect(self.rect(), QColor('#101010'))

        image = self._image

        if image is not None:
            if self.height() < 240:
                fast_scaler = QTransform()
                scale = 297/image.height()
                if self.mirror:
                    fast_scaler.scale(-scale, scale)
                else:
                    fast_scaler.scale(scale, scale)
                rect = event.rect()
                painter.drawPixmap(rect, QPixmap.fromImage(image.transformed(fast_scaler)).scaledToHeight(self.height(), Qt.SmoothTransformation), rect)
            else:
                transform = QTransform()
                scale = min(self.width()/image.width(), self.height()/image.height())
                if self.mirror:
                    transform.translate((self.width() + image.width()*scale)/2, (self.height() - image.height()*scale)/2)
                    transform.scale(-scale, scale)
                else:
                    transform.translate((self.width() - image.width()*scale)/2, (self.height() - image.height()*scale)/2)
                    transform.scale(scale, scale)

                inverse_transform, invertible = transform.inverted()
                rect = inverse_transform.mapRect(event.rect()).adjusted(-1, -1, 1, 1).intersected(image.rect())

                painter.setTransform(transform)

                if self.height() > 400:
                    painter.drawPixmap(rect, QPixmap.fromImage(image), rect)
                else:
                    painter.drawImage(rect, image, rect)

        painter.end()
开发者ID:AGProjects,项目名称:blink-qt,代码行数:39,代码来源:video.py

示例10: paint

# 需要导入模块: from PyQt5.QtGui import QTransform [as 别名]
# 或者: from PyQt5.QtGui.QTransform import translate [as 别名]
    def paint(self, qp: QPainter, option: QStyleOptionGraphicsItem, widget: QWidget=None):
        p = self.parentItem()
        pRot = p.rotation()
        trans = QTransform()
        trans.rotate(-p.rotation())

        p2Scene = p.mapToScene(p.p2)
        if 0 <= pRot < 90:
            trans.translate(p2Scene.x() - self.boundingRect().width(), p2Scene.y())
        elif 90 <= pRot < 180:
            trans.translate(p2Scene.x(), p2Scene.y())
        elif 180 <= pRot < 270:
            trans.translate(p2Scene.x(), p2Scene.y() - self.boundingRect().height())
        elif 270 <= 360:
            trans.translate(p2Scene.x() - self.boundingRect().width(), p2Scene.y() - self.boundingRect().height())
        self.setTransform(trans)

        super().paint(qp, option, widget)
开发者ID:Manko10,项目名称:WekaVisualizer,代码行数:20,代码来源:StarPlot.py

示例11: rotate_image

# 需要导入模块: from PyQt5.QtGui import QTransform [as 别名]
# 或者: from PyQt5.QtGui.QTransform import translate [as 别名]
    def rotate_image(self, rotation):
        if self.original_image is not None:
            print(rotation)
            # Rotate the original and viewable image to ensure a constant workflow when modifying from canvas
            matrix = QTransform()
            matrix.translate(self.image.width() / 2, self.image.height() / 2)
            matrix.rotate(rotation)
            matrix.translate(-self.image.width() / 2, -self.image.height() / 2)
            
            # Save transformed image
            self.image = self.image.transformed(matrix)
           
            original_matrix = QTransform()
            original_matrix.translate(self.original_image.width() / 2, self.original_image.height() / 2)
            original_matrix.rotate(rotation)
            original_matrix.translate(-self.original_image.width() / 2, -self.original_image.height() / 2)
            
            # Save transformed image
            self.original_image = self.original_image.transformed(original_matrix)

            self.scene.clear()
            self.scene.addItem(CustomQGraphicsPixmapItem(QPixmap.fromImage(self.image), self.c_width, self.c_height))
            self.scene.update()
开发者ID:gimu,项目名称:hitagi-reader.py,代码行数:25,代码来源:canvas.py

示例12: draw

# 需要导入模块: from PyQt5.QtGui import QTransform [as 别名]
# 或者: from PyQt5.QtGui.QTransform import translate [as 别名]
    def draw(self, painter, height, factor):
        painter.save()
        painter.translate(0, -CURVE_Y_OFFSET_COMPENSATION)
        painter.scale(1, -factor)
        painter.translate(0, -self.value_min)

        pen = QPen()
        pen.setCosmetic(True)
        pen.setWidth(0)
        pen.setColor(Qt.black)

        painter.setPen(pen)

        if DEBUG:
            painter.fillRect(QRectF(0, self.value_min,
                                    -self.axis_line_thickness - self.tick_mark_size_large, self.value_max - self.value_min),
                             Qt.cyan)

        # axis line
        painter.drawLine(QLineF(-self.axis_line_thickness, self.value_min,
                                -self.axis_line_thickness, self.value_max))

        # ticks
        tick_text_values = []
        value = self.value_min

        while fuzzy_leq(value, self.value_max):
            tick_text_values.append(value)

            painter.drawLine(QLineF(-self.axis_line_thickness, value,
                                    -self.axis_line_thickness - self.tick_mark_size_large, value))

            for i in range(1, self.step_subdivision_count):
                subvalue = value + (self.step_size * i / self.step_subdivision_count)

                if not fuzzy_leq(subvalue, self.value_max):
                    break

                if i % 2 == 0 and self.step_subdivision_count % 2 == 0:
                    tick_mark_size = self.tick_mark_size_medium
                else:
                    tick_mark_size = self.tick_mark_size_small

                painter.drawLine(QLineF(-self.axis_line_thickness, subvalue,
                                        -self.axis_line_thickness - tick_mark_size, subvalue))

            value += self.step_size

        painter.restore()

        painter.setFont(self.tick_text_font)

        tick_text_x = -self.axis_line_thickness - \
                      self.tick_mark_size_large - \
                      self.tick_mark_to_tick_text - \
                      self.tick_text_max_width
        tick_text_width = self.tick_text_max_width
        tick_text_height = self.tick_text_height_half * 2

        transform = QTransform()

        transform.translate(0, -CURVE_Y_OFFSET_COMPENSATION)
        transform.scale(1, -factor)
        transform.translate(0, -self.value_min)

        for value in tick_text_values:
            tick_text_point = transform.map(QPointF(tick_text_x, value))

            tick_text_x = tick_text_point.x()
            tick_text_y = tick_text_point.y() - self.tick_text_height_half

            if DEBUG:
                painter.fillRect(tick_text_x, tick_text_y,
                                 tick_text_width, tick_text_height,
                                 Qt.yellow)

            painter.drawText(tick_text_x, tick_text_y, tick_text_width, tick_text_height,
                             Qt.TextDontClip | Qt.AlignRight | Qt.AlignVCenter,
                             self.tick_value_to_str(value))

        # title
        title_width = height
        title_height = self.title_text_height

        if self.title_text_pixmap == None or self.title_text_pixmap.size() != QSize(title_width, title_height):
            self.title_text_pixmap = QPixmap(title_width + 100, title_height + 100)

            self.title_text_pixmap.fill(QColor(0, 0, 0, 0))

            title_painter = QPainter(self.title_text_pixmap)

            if DEBUG:
                title_painter.fillRect(50, 50, title_width, title_height, Qt.yellow)

            title_painter.setFont(self.title_text_font)
            title_painter.drawText(50, 50, title_width, title_height,
                                   Qt.TextWordWrap | Qt.TextDontClip | Qt.AlignHCenter | Qt.AlignTop,
                                   self.title_text)

            title_painter = None
#.........这里部分代码省略.........
开发者ID:Tinkerforge,项目名称:brickv,代码行数:103,代码来源:plot_widget.py

示例13: paintEvent

# 需要导入模块: from PyQt5.QtGui import QTransform [as 别名]
# 或者: from PyQt5.QtGui.QTransform import translate [as 别名]
	def paintEvent(self, event):
		  
		painter = QPainter(self)
		painter.setPen(self.pen)
		painter.setBrush(self.brush)
		if self.antialiased:
			painter.setRenderHint(QPainter.Antialiasing)

		angle_step = 360 / self.n_states

		painter.save()	#Save_1. Save the state of the system (push matrix)
		painter.translate(self.dist_center.x(), self.dist_center.y())		# go to the center of the render area
		painter.rotate(-180)	#to start painting from the left side of the circle (clockwise)

		#center of the circumference where through we are going to paint our states 
		x = self.dist_radius * math.cos(0)	
		y = self.dist_radius * math.sin(0)


		for h in range(self.n_states):

			rot = angle_step * h 	# each state is equidistant from the others. We paint them in circles

			painter.save()			#Save_2
			painter.rotate(rot)		#now our system is pointing to the next state to be drawn
			painter.translate(x,y)	#now our origin is in the center of the next state to be drawn

			#if the state is active, fill it green
			if self.machine.getState(h).isActive():	
				painter.setBrush(self.greenGradientBrush)			
			painter.drawEllipse(QPoint(0,0), self.state_radius, self.state_radius)	#draw the new state

			#global position of transformed coordinates (before any transformation, origin at top-left corner)
			gx = painter.worldTransform().map(QPoint(0,0)).x()
			gy = painter.worldTransform().map(QPoint(0,0)).y()
			self.machine.getState(h).setPos(gx, gy)		#store the center of the state without any transformation applied

			# text transformation. Our origin is still in the center of the current state
			painter.save()			#Save_3
			painter.rotate(180)		#making the text go vertical
			painter.rotate(-rot)	#undoing the rotation made for painting the state. No the text is horizontal
			font = painter.font();
			font.setPixelSize(self.state_radius*.4);
			painter.setFont(font);
			rect = QRect(-self.state_radius, -self.state_radius, self.state_radius*2, self.state_radius*2)
			painter.drawText(rect, Qt.AlignCenter, self.machine.getState(h).getName());
			painter.restore()	#Restore_3
			#end text transformation

			painter.restore()	#Restore_2
			
		painter.restore()	#Restore_1. Restore the state of the system (pop matrix)

		
		#drawing transitions. Line between states
		painter.save()	# Save_4
		pptv = QTransform()		#Define a new transformation. Needed to rotate the system along other axis than Z
		pptv.translate(0, self.height())	#We are now at the bottom-left corner of the screen
		pptv.rotate(-180, Qt.XAxis)			#Rotate along the X-axis so now we are in a typical cartesian system.
		painter.setTransform(pptv)			#Apply the transformation
		states = self.machine.getStates()
		for state in states:
			transitions = state.getTransitions()
			for transition in transitions:
				#get the center of the origin and destination states in our current system state
				orig = QPoint(state.getPos()[0], state.getPos()[1])
				end = QPoint(self.machine.getState(transition.getStateEnd()).getPos()[0], self.machine.getState(transition.getStateEnd()).getPos()[1])
				# get those coordinates without transformation
				orig2 = QPoint(painter.worldTransform().map(orig))
				end2 = QPoint(painter.worldTransform().map(end))

				#get the angle between states centers and the horizon
				angle = math.atan2(end2.y() - orig2.y(), end2.x() - orig2.x())

				#get the coordinates of the starting point of the transition (it starts in the bound of the state, not in the center)
				newX = self.state_radius * math.cos(angle) + orig2.x()
				newY = self.state_radius * math.sin(angle) + orig2.y()
				#now the transition starts at the border, not in the center
				orig2.setX(newX)
				orig2.setY(newY)

				#same for the destination state
				angle2 = math.atan2(orig2.y() - end2.y(), orig2.x() - end2.x())
				newX2 = self.state_radius * math.cos(angle2) + end2.x()
				newY2 = self.state_radius * math.sin(angle2) + end2.y()
				end2.setX(newX2)
				end2.setY(newY2)

				#draw the line between the origin and destination states
				painter.drawLine(orig2, end2)
				#get the start and the end of the transition untransformed
				init = QPoint(painter.worldTransform().map(orig2))
				end = QPoint(painter.worldTransform().map(end2))
				#store that info
				transition.setOrig(init.x(), init.y())
				transition.setDest(end.x(), end.y())	
				transition.setAngle(angle)
		painter.restore() #Restore_4


#.........这里部分代码省略.........
开发者ID:fqez,项目名称:sandbox,代码行数:103,代码来源:gui.py

示例14: _paint_crop

# 需要导入模块: from PyQt5.QtGui import QTransform [as 别名]
# 或者: from PyQt5.QtGui.QTransform import translate [as 别名]
    def _paint_crop(self, painter, option, index):
        """Paints the crop
        """
        source_rect = index.data(RectRole)
        crop_rect = self.crop_rect.translated(option.rect.topLeft())
        angle = index.data(RotationRole)

        # Target rect with same aspect ratio as source
        source_aspect = float(source_rect.width()) / source_rect.height()
        crop_aspect = float(crop_rect.width()) / crop_rect.height()

        # True if the item has been rotated by a multiple of 90 degrees
        perpendicular = 1 == (angle / 90) % 2

        # Some nasty logic to compute the target rect
        if perpendicular:
            crop_aspect = 1.0 / crop_aspect

        if source_aspect > 1.0:
            # Crop is wider than is is tall
            if crop_aspect > source_aspect:
                fit_to = 'height'
                f = 1.0 / source_aspect
            else:
                fit_to = 'width'
                f = source_aspect
        else:
            # Crop is taller than is is wide
            if crop_aspect < source_aspect:
                fit_to = 'width'
                f = source_aspect
            else:
                fit_to = 'height'
                f = 1.0 / source_aspect

        if perpendicular:
            if 'width' == fit_to:
                size = QSize(crop_rect.height(),
                             crop_rect.height() / f)
            else:
                size = QSize(crop_rect.width() / f,
                             crop_rect.width())
        else:
            if 'width' == fit_to:
                size = QSize(crop_rect.width(),
                             crop_rect.width() / f)
            else:
                size = QSize(crop_rect.height() / f,
                             crop_rect.height())

        target_rect = QRect(crop_rect.topLeft(), size)
        target_rect.moveCenter(option.rect.center())

        # Draw rotated
        if angle:
            t = QTransform()
            t.translate(option.rect.width() / 2 + option.rect.left(),
                        option.rect.height() / 2 + option.rect.top())
            t.rotate(angle)
            t.translate(-option.rect.width() / 2 - option.rect.left(),
                        -option.rect.height() / 2 - option.rect.top())

        with painter_state(painter):
            if angle:
                painter.setTransform(t)
            painter.drawPixmap(target_rect, index.data(PixmapRole), source_rect)

            if QStyle.State_Selected & option.state:
                painter.setPen(QPen(Qt.white, 1, Qt.SolidLine))
                painter.drawRect(target_rect)
开发者ID:NaturalHistoryMuseum,项目名称:inselect,代码行数:72,代码来源:object.py

示例15: SchView

# 需要导入模块: from PyQt5.QtGui import QTransform [as 别名]
# 或者: from PyQt5.QtGui.QTransform import translate [as 别名]
class SchView(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self._transform = QTransform()
        # set up transform
        self._transform.translate(0, 0)
        # set to 100 px = 1 inch
        self._transform.scale(100.0/Coord.inchToSch(1), -100.0/Coord.inchToSch(1))
        self._mousePos = QPoint()
        self._wheelAngle = 0
        self._ctrl = None
        self.setMouseTracking(True)
        self.setFocusPolicy(Qt.StrongFocus)

    def setCtrl(self, ctrl):
        self._ctrl = ctrl

    def paintEvent(self, event):
        painter = QPainter(self)
        # erase background
        painter.setBackground(QBrush(Layer.color(LayerType.background)))
        painter.setClipping(True)
        painter.eraseRect(self.rect())
        # draw document
        if self._ctrl is not None:
            # draw grid
            painter.setRenderHint(QPainter.Antialiasing, False)
            pen = QPen(Layer.color(LayerType.grid))
            pen.setCapStyle(Qt.RoundCap)
            pen.setJoinStyle(Qt.RoundJoin)
            pen.setWidth(0)
            painter.setTransform(self._transform)
            painter.setPen(pen)
            self._drawGrid(painter)
            # draw drawables
            # painter.setRenderHint(QPainter.Antialiasing)
            for d in self._ctrl.getDrawables():
                d.draw(painter)
        painter.end()

    def _drawGrid(self, painter):
        g = self._ctrl.grid
        if self._transform.map(QLine(QPoint(0, 0), QPoint(g, 0))).dx() <= 5:
            return  # grid points too close, don't draw grid
        viewport = self._transform.inverted()[0].mapRect(self.rect())
        startX = int(viewport.x() / g) * g
        startY = int(viewport.y() / g) * g
        endX = viewport.x() + viewport.width()
        endY = viewport.y() + viewport.height()
        pts = QPolygon((QPoint(i[0], i[1]) for i in product(range(startX, endX, g),
                                                            range(startY, endY, g))))
        painter.drawPoints(pts)

    def _handleEvent(self, event: Event):
        if self._ctrl is not None:
            self._ctrl.handleEvent(event)

    def zoom(self, factor, pos):
        self.recenter(pos)
        p = self._transform.inverted()[0].map(self.rect().center())
        test = QTransform(self._transform)
        test.scale(factor, factor)
        # check if the bounding rectangle does not enclose the view
        # refuse to zoom out (factor < 1) if this is the case
        # XXX TODO
        self._transform.scale(factor, factor)
        self.recenter(p, True)

    def recenter(self, pt=None, world=False):
        if pt is None:
            pt = self._mousePos
        ctr = self._transform.inverted()[0].map(self.rect().center())
        if not world:
            pt = self._transform.inverted()[0].map(pt)
        ctr -= pt
        self._transform.translate(ctr.x(), ctr.y())
        # move cursor to center of window
        QCursor.setPos(self.mapToGlobal(self.rect().center()))
        self.update()

    def mouseMoveEvent(self, e):
        if e.buttons() & Qt.MidButton:
            dl = QLine(QPoint(0, 0), e.pos() - self._mousePos)
            dl = self._transform.inverted()[0].map(dl)
            self._transform.translate(dl.dx(), dl.dy())
            self.update()
        self._handleEvent(Event(evType=Event.Type.MouseMoved,
                                pos=self._transform.inverted()[0].map(e.pos())))
        self._mousePos = e.pos()

    def mousePressEvent(self, e):
        if e.button() == Qt.LeftButton:
            self._handleEvent(Event(evType=Event.Type.MousePressed,
                                    pos=self._transform.inverted()[0].map(e.pos())))

    def mouseReleaseEvent(self, e):
        if e.button() == Qt.LeftButton:
            self._handleEvent(Event(evType=Event.Type.MouseReleased,
                                    pos=self._transform.inverted()[0].map(e.pos())))

#.........这里部分代码省略.........
开发者ID:olegizyumin1987,项目名称:pyschem,代码行数:103,代码来源:view.py


注:本文中的PyQt5.QtGui.QTransform.translate方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。