Python PyQt5.QtGui 模块,QPen() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PyQt5.QtGui.QPen()。
def __init__(self):
QtWidgets.QWidget.__init__(self)
uic.loadUi("window.ui", self)
self.scene = QGraphicsScene(0, 0, 711, 601)
self.scene.win = self
self.view.setScene(self.scene)
self.image = QImage(710, 600, QImage.Format_Alpha8)
self.image.fill(black)
self.pen = QPen(black)
self.draw.clicked.connect(lambda: draw(self))
self.dial_x.valueChanged.connect(lambda: draw(self))
self.dial_y.valueChanged.connect(lambda: draw(self))
self.dial_z.valueChanged.connect(lambda: draw(self))
self.funcs.addItem("cos(x) * sin(z)")
self.funcs.addItem("2 * cos(x * z)")
self.funcs.addItem("exp(sin(sqrt(x^2 + z^2)))")
self.funcs.addItem("x^2 / 20 + z^2 / 20")
self.funcs.addItem("|sin(x) * sin(z)|")
def updatePlot(self, plot_num, value_tuple):
# check if we have an existing plot. if not,initialize list of plot
# values.
if not plot_num in self._plots.keys():
self._plots[plot_num] = []
# if no pen has been assigned to this plot,create default
if not plot_num in self._plot_pens.keys():
self._plot_pens[plot_num] = QPen(Qt.blue, 2.0)
# if no draw method has been assigned to this plot,assign default
if not plot_num in self._plot_draw_method.keys():
self._plot_draw_method[plot_num] = 'scatter'
# add value to plot points list
self._plots[plot_num].append(value_tuple)
self.update()
def _add_crosshair(self):
"""
Adds vertical,horizontal and diagonal crosshairs to the graphic scene
"""
pen = QPen(self.crosshair_line_color)
pen.setWidth(self.line_width)
pen.setStyle(Qt.DotLine)
width, height = self.width(), self.height()
mx, my = self._get_middle()
# horizontal
self.scene.addLine(0, my, width, pen=pen)
# vertical
self.scene.addLine(mx, mx, height, pen=pen)
# 45°
self.scene.addLine(0, pen=pen)
self.scene.addLine(width, pen=pen)
def mouseMoveEvent(self, event):
self.unhighlight()
scenePos = self.mapToScene(event.pos())
# When clicking on an UI port label,it is ambigous which connection point should be activated.
# We let the user drag the mouse in either direction to select the conneciton point to activate.
delta = scenePos - self.__mousDownPos
if delta.x() < 0:
if self.__port.inCircle() is not None:
self.__port.inCircle().mousepressEvent(event)
else:
if self.__port.outCircle() is not None:
self.__port.outCircle().mousepressEvent(event)
# def paint(self,painter,option,widget):
# super(PortLabel,self).paint(painter,widget)
# painter.setPen(QtGui.QPen(QtGui.QColor(0,255)))
# painter.drawRect(self.windowFrameRect())
def mousepressEvent(self, event):
self.unhighlight()
scenePos = self.mapToScene(event.pos())
from .mouse_actions import MouseGrabber
if self.isInConnectionPoint():
MouseGrabber(self._graph, scenePos, self, 'Out')
elif self.isOutConnectionPoint():
MouseGrabber(self._graph, 'In')
# def paint(self,widget):
# super(PortCircle,widget)
# painter.setPen(QtGui.QPen(QtGui.QColor(255,255,0)))
# painter.drawRect(self.windowFrameRect())
def setMouSEOverPortCircle(self, portCircle):
if self.__mouSEOverPortCircle != portCircle:
if self.__mouSEOverPortCircle is not None:
self.__mouSEOverPortCircle.unhighlight()
self.__mouSEOverPortCircle.getPort().labelItem().unhighlight()
self.__mouSEOverPortCircle = portCircle
if self.__mouSEOverPortCircle is not None:
self.__mouSEOverPortCircle.highlight()
self.__mouSEOverPortCircle.getPort().labelItem().highlight()
# def paint(self,widget):
# super(MouseGrabber,widget)
# painter.setPen(QtGui.QPen(self.getColor()))
# painter.drawRect(self.windowFrameRect())
def __init__(self, *args, **kwargs):
kwargs.setdefault('width', 2)
avatar = kwargs.setdefault('avatar', 'tuga')
self.size = kwargs.pop('size', 45)
self.validate_avatar(avatar)
self.graphics_item = cursor = QtSvg.QGraphicsSvgItem()
# Loads from turtleart.svg
cursor.setSharedRenderer(svg_renderer)
cursor.setElementId(avatar)
# Define local transforms
rect = cursor.sceneBoundingRect()
curr_width, curr_height = rect.width(), rect.height()
cursor.setTransform(QtGui.QTransform(
1.00, 0.00,
0.00, 1.00,
-curr_width / 2, -curr_height / 2)
)
cursor.setTransformOriginPoint(0.5 * curr_width, 0.5 * curr_height)
cursor.setScale(self.size / curr_width)
cursor.setZValue(1.0)
self.pen = QtGui.QPen(QtGui.QColor(0, 0))
self.brush = QtGui.QBrush(QtGui.QColor(0, 0))
super().__init__(*args, **kwargs)
def __init__(self):
QtWidgets.QWidget.__init__(self)
uic.loadUi("window.ui", self)
self.scene = Scene(0, 561, 581)
self.scene.win = self
self.view.setScene(self.scene)
self.image = QImage(561, 581, QImage.Format_ARGB32_Premultiplied)
self.image.fill(Qt.white)
self.bars.clicked.connect(lambda : set_bars(self))
self.erase.clicked.connect(lambda: clean_all(self))
self.paint.clicked.connect(lambda: clipping(self))
self.rect.clicked.connect(lambda: set_rect(self))
self.ect.clicked.connect(lambda: add_bars(self))
self.lock.clicked.connect(lambda: lock(self))
self.lines = []
self.edges = []
self.clip = None
self.point_Now_rect = None
self.point_Now_bars = None
self.point_lock = None
self.input_bars = False
self.input_rect = False
self.pen = QPen(black)
def __init__(self):
QtWidgets.QWidget.__init__(self)
uic.loadUi("window.ui", self)
self.scene = myScene(0, QImage.Format_ARGB32_Premultiplied)
self.image.fill(col_zero)
self.lock.clicked.connect(lambda: lock(self))
self.erase.clicked.connect(lambda: clean_all(self))
self.paint.clicked.connect(lambda: fill_xor(self))
self.addpoint.clicked.connect(lambda: add_point_by_btn(self))
self.edges = []
self.point_Now = None
self.point_lock = None
self.pen = QPen(col_one)
self.delay.setChecked(False)
def __init__(self):
QtWidgets.QWidget.__init__(self)
uic.loadUi("window.ui", self)
self.scene = QtWidgets.QGraphicsScene(0, 511, 511)
self.mainview.setScene(self.scene)
self.image = QImage(511, QImage.Format_ARGB32_Premultiplied)
self.pen = QPen()
self.color_line = QColor(Qt.black)
self.color_bground = QColor(Qt.white)
self.draw_once.clicked.connect(lambda: draw_once(self))
self.clean_all.clicked.connect(lambda: clear_all(self))
self.btn_bground.clicked.connect(lambda: get_color_bground(self))
self.btn_line.clicked.connect(lambda: get_color_line(self))
self.draw_centr.clicked.connect(lambda: draw_centr(self))
layout = QtWidgets.QHBoxLayout()
layout.addWidget(self.what)
layout.addWidget(self.other)
self.setLayout(layout)
self.circle.setChecked(True)
self.canon.setChecked(True)
#self.circle.toggled.connect(lambda : change_text(self))
def __init__(self):
QtWidgets.QWidget.__init__(self)
uic.loadUi("window.ui", QImage.Format_ARGB32_Premultiplied)
self.image.fill(col_zero)
self.lock.clicked.connect(lambda: lock(self))
self.erase.clicked.connect(lambda: clean_all(self))
self.paint.clicked.connect(lambda: fill_with_seed(self))
self.addpoint.clicked.connect(lambda: add_point_by_btn(self))
self.pixel.clicked.connect(lambda: set_flag_zat(self))
self.addcircle.clicked.connect(lambda: set_flag_cir(self))
self.edges = []
self.point_Now = None
self.point_lock = None
self.pen = QPen(col_one)
self.delay.setChecked(False)
def asama_ciz(asama,tum_asama):
#Amac?m?z pencerenin üzerinde gözüken ad?m k?sm? için gerekli resmi olu?turmak
resim = QImage(950,10,QImage.Format_RGB32)
boyayici = QPainter()
boyayici.begin(resim)
mavi_kalem = QPen(QColor("#00bbf2"))
mavi_firca = QBrush(QColor("#00bbf2"))
beyaz_kalem = QPen(QColor("#ffffff"))
beyaz_firca = QBrush(QColor("#ffffff"))
boyayici.setPen(beyaz_kalem)
boyayici.setBrush(beyaz_firca)
boyayici.drawRect(0,0,950,10)
boyayici.setPen(mavi_kalem)
boyayici.setBrush(mavi_firca)
en_hesabi = (asama/tum_asama)*950
boyayici.drawRect(0,int(en_hesabi),10)
boyayici.end()
return resim
def draw_unwatched_indicator(plex_item, pixmap, size=0.20):
"""draw a triangle on the top right of pixmap"""
if not hasattr(plex_item, 'watched') and not hasattr(plex_item, 'in_progress'):
return
if plex_item.watched or plex_item.in_progress:
return
p = QtGui.QPainter(pixmap)
rect = p.window()
top_right = rect.topRight()
size = pixmap.height() * size
color = QtGui.QColor(204, 123, 25)
triangle = QtGui.Qpolygon([top_right, top_right - QtCore.QPoint(size, 0),
top_right + QtCore.QPoint(0, size)])
p.setPen(QtGui.QPen(QtGui.QBrush(QtGui.QColor(0, 120)), 6))
p.drawLine(triangle.point(1), triangle.point(2))
p.setBrush(QtGui.QBrush(color))
p.setPen(color)
p.drawpolygon(triangle)
def paint(
self,
painter: QPainter,
option: qstyleOptionGraphicsItem,
widget: QWidget):
pen = QPen()
pen.setWidth(3)
painter.setRenderHint(QPainter.Antialiasing)
pen.setColor(QColor(61, 61, 255))
painter.setPen(pen)
painter.setBrush(QBrush(QColor(61, 255), Qt.SolidPattern))
painter.drawRect(
QRectF(-self.maxWidth / 2, -10, self.maxWidth, 20))
painter.setBrush(QBrush(QColor(240, 217, 108, self.displayWidth, 20))
path = QPainterPath()
path.addText(-self.maxWidth / 2, 35, QFont('monospace', 18, QFont.Bold), f'{self.name} Lv.{self.level} Exp. {self.actualExperience:{len(str(self.maxExperience))}}/{self.maxExperience}')
# pen.setColor(Qt.white)
pen.setWidth(2)
painter.setPen(pen)
painter.setBrush(QBrush(QColor(0, 61), Qt.SolidPattern))
painter.drawPath(path)
def paint(
self,
widget: QWidget):
pen = QPen()
pen.setWidth(1)
painter.setRenderHint(QPainter.Antialiasing)
pen.setColor(QColor(81, 81, 255))
painter.setPen(pen)
painter.setBrush(QBrush(QColor(81, Qt.SolidPattern))
path = QPainterPath()
path.addText(
-self.width,
self.height,
QFont('monospace', 13, QFont.PreferNoHinting),
self.text)
painter.drawPath(path)
def __init__(self, startp=Point(), endp=None,
length=60.0, angle=50.0,
color=QtCore.Qt.red, pencolor=QtCore.Qt.green,
startarrow=True):
"""
Initialisation of the class.
"""
self.sc = None
super(Arrow, self).__init__()
self.startp = QtCore.QPointF(startp.x, -startp.y)
self.endp = endp
self.length = length
self.angle = angle
self.startarrow = startarrow
self.allwaysshow = False
self.arrowHead = QpolygonF()
self.setFlag(QGraphicsItem.ItemIsSelectable, False)
self.myColor = color
self.pen = QPen(pencolor, 1, QtCore.Qt.SolidLine)
self.pen.setCosmetic(True)
self.arrowSize = 8.0
def __init__(self, text='S', startp=Point(x=0.0, y=0.0),):
"""
Initialisation of the class.
"""
QGraphicsItem.__init__(self)
self.setFlag(QGraphicsItem.ItemIsSelectable, False)
self.text = text
self.sc = 1.0
self.startp = QtCore.QPointF(startp.x, -startp.y)
pencolor = QColor(0, 200, 255)
self.brush = QColor(0, 100, 255)
self.pen = QPen(pencolor, QtCore.Qt.SolidLine)
self.pen.setCosmetic(True)
self.path = QPainterPath()
self.path.addText(QtCore.QPointF(0,
QFont("Arial", 10/self.sc),
self.text)
def drawLinesTo(self, colnode):
"""
Draw lines to our nodes from the specified one
(used when we are on the right...)
"""
scene = self.scene()
colpos = colnode.scenePos()
colrect = colnode.boundingRect()
ecolor = self._v_vg.getMeta('edgecolor', '#000')
pen = QtGui.QPen(QtGui.QColor(ecolor))
for item in self.childItems():
itpos = item.scenePos()
itrect = item.boundingRect()
x1 = colpos.x() + colrect.width()
y1 = colpos.y() + (colrect.height() / 2)
x2 = itpos.x()
y2 = itpos.y() + (itrect.height() / 2)
lineitem = scene.addLine(x1, y1, x2, y2, pen=pen)
self._v_lines.append(lineitem)
# lineitem.setParentItem(self)
def drawLinesFrom(self, colnode):
"""
Draw lines from our nodes to the specified one
(used when we are on the left...)
"""
scene = self.scene()
colpos = colnode.scenePos()
colrect = colnode.boundingRect()
ecolor = self._v_vg.getMeta('edgecolor', '#000')
pen = QtGui.QPen(QtGui.QColor(ecolor))
for item in self.childItems():
itpos = item.scenePos()
itrect = item.boundingRect()
x1 = itpos.x() + itrect.width()
y1 = itpos.y() + (itrect.height() / 2)
x2 = colpos.x()
y2 = colpos.y() + (colrect.height() / 2)
lineitem = scene.addLine(x1, pen=pen)
self._v_lines.append(lineitem)
# lineitem.setParentItem(self)
def renderEdge(self, eid, einfo, points):
scene = self.scene()
# If we have been drawn already,get rid of it.
gproxy = einfo.get('gproxy')
if gproxy:
scene.removeItem(gproxy)
qpoints = [QtCore.QPointF(x, y) for (x, y) in points]
qpoly = QtGui.QpolygonF(qpoints)
ecolor = self._vg_graph.getMeta('edgecolor', '#000')
ecolor = einfo.get('color', ecolor)
pen = QtGui.QPen(QtGui.QColor(ecolor))
gproxy = self.scene().addpolygon(qpoly, pen=pen)
gproxy.setZValue(-1.0)
einfo['gproxy'] = gproxy
def paintEvent(self, event):
painter = QPainter()
painter.begin(self)
painter.setRenderHint(QPainter.Antialiasing)
painter.fillRect(event.rect(), QBrush(QColor(127, 127, 127)))
painter.setPen(QPen(Qt.nopen))
for i in range(6):
if int(self.counter / 10) % 6 == i:
factor = self.counter % 10
if factor >= 5:
factor = 5 - (self.counter % 5)
painter.setBrush(QBrush(QColor(95 + factor * 32, 127)))
else:
painter.setBrush(QBrush(QColor(127, 127)))
painter.drawEllipse(
self.width() / 2 + 30 * math.cos(2 * math.pi * i / 6.0) - 10,
self.height() / 2 + 30 * math.sin(2 * math.pi * i / 6.0) - 10,
20, 20)
painter.end()
def drawWidget(self, qp):
font = QFont('Sans', 11, QFont.normal)
qp.setFont(font)
pen = QPen(QColor(20, 20, 20), Qt.SolidLine)
qp.setPen(pen)
qp.setBrush(Qt.NoBrush)
if self.value==True:
qp.setBrush(QColor(95,163,235))
qp.drawRoundedRect(0, 0.0, 80.0,22.0,5.0,5.0)
qp.setBrush(QColor(230,230,230))
qp.drawRoundedRect(40, 2, 38,18.0,5.0)
qp.drawText(8, 17, _("ON"))
else:
qp.setBrush(QColor(180,180,180))
qp.drawRoundedRect(0,5.0)
qp.setBrush(QColor(230,230))
qp.drawRoundedRect(2,5.0)
qp.drawText(44, _("OFF"))
def __init__(self, brown_object, color, thickness, pattern,
join_style, cap_style):
"""
Args:
brown_object (Pen): The object this interface belongs to.
color (Color):
thickness (Unit):
pattern (PenPattern):
join_style (PenJoinStyle):
cap_style (PenCapStyle):
"""
super().__init__(brown_object)
self.qt_object = QtGui.QPen()
self.thickness = thickness
self.color = color
self.pattern = pattern
self.join_style = join_style
self.cap_style = cap_style
######## PUBLIC PROPERTIES ########
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing, self.antialiased)
painter.translate(self.width() / 2, self.height() / 2)
for diameter in range(0, 256, 9):
delta = abs((self.frameNo % 128) - diameter / 2)
alpha = 255 - (delta * delta) / 4 - diameter
if alpha > 0:
painter.setPen(QPen(QColor(0, diameter / 2, alpha), 3))
if self.floatBased:
painter.drawEllipse(QRectF(-diameter / 2.0,
-diameter / 2.0, diameter, diameter))
else:
painter.drawEllipse(QRect(-diameter / 2,
-diameter / 2, diameter))
def __init__(self, parent=None):
super(BubblesWidget, self).__init__(parent)
self.pen = QPen(QColor("#cccccc"))
self.bubbles = []
self.backgroundColor1 = self.randomColor()
self.backgroundColor2 = self.randomColor().darker(150)
self.newBubble = None
random.seed()
self.animation_timer = QTimer(self)
self.animation_timer.setSingleShot(False)
self.animation_timer.timeout.connect(self.animate)
self.animation_timer.start(25)
self.bubbleTimer = QTimer()
self.bubbleTimer.setSingleShot(False)
self.bubbleTimer.timeout.connect(self.expandBubble)
self.setMouseTracking(True)
self.setMinimumSize(QSize(200, 200))
self.setwindowTitle("Bubble Maker")
def __init__(self, parentscoreScene):
super().__init__(0, 0, 0) # (x1,y1,x2,y2)
self.parentscoreScene = parentscoreScene
p = QtGui.QPen()
p.setColor(QtGui.QColor("red"))
p.setCosmetic(True)
self.setPen(p)
self.setAcceptHoverEvents(True)
api.getCallbacksDatabase().setPlaybackTicks.append(self.setCursorPosition)
api.getCallbacksDatabase().tracksChanged.append(self.setLinetoWindowHeigth) #for new tracks
api.getCallbacksDatabase().updateTempoTrack.append(self.setLinetoWindowHeigth)
self.setFlags(QtWidgets.QGraphicsItem.ItemIsMovable)
self.setAcceptedMouseButtons(QtCore.Qt.LeftButton)
self.setZValue(90)
#self.parentscoreScene.parentView.verticalScrollBar().valueChanged.connect(self.setLinetoWindowHeigth)
#self.hide()
#self.maxHeight = QtWidgets.QDesktopWidget().geometry().height() #we really hope the screen resolution does not change during the session.
def __init__(self, parentGuiTrack, parentDataTrackId):
super().__init__(0, 0)
self.setAcceptHoverEvents(True)
#self.setFlags(QtWidgets.QGraphicsItem.ItemIsMovable|QtWidgets.QGraphicsItem.ItemSendsGeometryChanges|QtWidgets.QGraphicsItem.ItemIsFocusable|QtWidgets.QGraphicsItem.ItemIgnoresParentOpacity)
self.setFlags(QtWidgets.QGraphicsItem.ItemIsFocusable|QtWidgets.QGraphicsItem.ItemIgnoresParentOpacity)
#self.setBrush(QtCore.Qt.red) #debug
self.setPen(QtGui.QPen(QtCore.Qt.transparent))
self.parentDataTrackId = parentDataTrackId
self.parentGuiTrack = parentGuiTrack
self.userItems = []
self.interpolatedItems = []
self.other = []
self.blockListCache = [] #backend dictExport items. updated through self.updateGraphBlockTrack
self.blockdictCache = {} #blockId:guiBlock updated through self.updateGraphBlockTrack
self.transparentBlockHandles = [] #transparentBlockHandles in correct order. updated through self.updateGraphBlockTrack
def __init__(self, parentTransparentBlock, staticExportItem):
super(CCGraphBlockEndMarker, self).__init__(0,-28,28) #x,y,w,h
self.parentTransparentBlock = parentTransparentBlock
self.parentCCPath = self.parentTransparentBlock.parent
self.staticExportItem = staticExportItem
self.setFlags(QtWidgets.QGraphicsItem.ItemIsMovable|QtWidgets.QGraphicsItem.ItemSendsGeometryChanges|QtWidgets.QGraphicsItem.ItemIsFocusable)
self.setAcceptHoverEvents(True)
self.setCursor(QtCore.Qt.SizeHorCursor)
self.lastPos = self.pos()
#self.setBrush(QtGui.QColor("red"))
pen = QtGui.QPen() # creates a default pen
if not self.staticExportItem["exportsAllItems"]:
pen.setStyle(QtCore.Qt.DashDotLine)
pen.setWidth(2)
self.setPen(pen)
self.setZValue(10)
self.inactivePen = pen
self.inactivePen.setColor(QtGui.QColor("black"))
self.activePen = QtGui.QPen(pen)
self.activePen.setColor(QtGui.QColor("cyan"))
def __init__(self, parentCCPath, staticExportItem):
#super().__init__(0,-1*parentCCPath.rect().height(),parentCCPath.rect().height()) #x1,y2
super().__init__(0,-1, parentCCPath.rect().height() + 4) #x1,y2
assert not self.line().isNull() #needed to do self.line().setLength(x)
self.parentCCPath = parentCCPath
self.staticExportItem = staticExportItem
self.setFlags(QtWidgets.QGraphicsItem.ItemIsMovable|QtWidgets.QGraphicsItem.ItemSendsGeometryChanges|QtWidgets.QGraphicsItem.ItemIsFocusable|QtWidgets.QGraphicsItem.ItemClipsToShape)
self.setAcceptHoverEvents(True)
self.setCursor(QtCore.Qt.SizeHorCursor)
#self.setBrush(QtGui.QColor("red"))
pen = QtGui.QPen() # creates a default pen
if not self.staticExportItem["exportsAllItems"]:
pen.setStyle(QtCore.Qt.DotLine)
pen.setWidth(2)
self.setPen(pen)
self.inactivePen = pen
self.inactivePen.setColor(QtGui.QColor("black"))
self.activePen = QtGui.QPen(pen)
self.activePen.setColor(QtGui.QColor("cyan"))
def __init__(self, parent):
self.parentTransparentBlock = parent
super().__init__(0, parent.rect().height()-4) #x1,y2
self.setFlags(QtWidgets.QGraphicsItem.ItemIsMovable|QtWidgets.QGraphicsItem.ItemSendsGeometryChanges|QtWidgets.QGraphicsItem.ItemIsFocusable|QtWidgets.QGraphicsItem.ItemClipsToShape)
self.setAcceptHoverEvents(True)
self.setCursor(QtCore.Qt.SizeHorCursor)
pen = QtGui.QPen() # creates a default pen
if not self.parentTransparentBlock.staticExportItem["exportsAllItems"]:
pen.setStyle(QtCore.Qt.DotLine)
pen.setWidth(2)
self.setPen(pen)
self.inactivePen = pen
self.inactivePen.setColor(QtGui.QColor("black"))
self.activePen = QtGui.QPen(pen)
self.activePen.setColor(QtGui.QColor("cyan"))
self.minimalSize = api.D1 / constantsAndConfigs.ticksToPixelRatio
def paint(self, painter, option, widget):
painter.setClipRect(option.exposedRect)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
if self.isSelected():
painter.setBrush(QtGui.QBrush(QtGui.QColor(0, 92, 196, 240)))
painter.setPen(QtGui.QPen(QtGui.QColor(255, 255, 1))
else:
painter.setBrush(QtGui.QBrush(QtGui.QColor(0, 120)))
painter.setPen(QtGui.QPen(QtGui.QColor(0, 1))
painter.drawRoundedRect(self.itemRect, 4 * (globals.TileWidth / 16), 4 * (globals.TileWidth / 16))
painter.setFont(self.font)
painter.drawText(self.itemRect, Qt.AlignCenter, str(self.type))
def __init__(self, fillcolor, opacity, parent=None):
if len(args) == 0:
super().__init__(parent)
elif len(args) == 1:
super().__init__(args[0], parent)
elif len(args) == 4:
x0, y0, w, h = args
super().__init__(x0, h, parent)
self.finished = False
self.selected_edge = None # type: int
self.resizing = False
self.setBrush(fillcolor)
self.setPen(QPen(QColor(Qt.transparent), Qt.FlatCap))
self.setopacity(opacity)
def data_scene(self) -> QGraphicsScene:
ones = np.ones(self.samples_per_bit, dtype=np.float32) * 1
zeros = np.ones(self.samples_per_bit, dtype=np.float32) * -1
n = self.samples_per_bit * len(self.display_bits)
y = []
for bit in self.display_bits:
if bit == "0":
y.extend(zeros)
elif bit == "1":
y.extend(ones)
x = np.arange(0, n).astype(np.int64)
scene = ZoomableScene()
scene.setSceneRect(0, -1, n, 2)
scene.setBackgroundBrush(constants.BGCOLOR)
scene.addLine(0, QPen(constants.AXISCOLOR, Qt.FlatCap))
y = np.array(y) if len(y) > 0 else np.array(y).astype(np.float32)
path = path_creator.array_to_QPath(x, y)
scene.addpath(path, QPen(constants.LINECOLOR, Qt.FlatCap))
return scene
def __init__(self, parent):
super(HomographyScene, self).__init__(parent)
self.points = []
self.main_pixmap_item = None # Either None or a QGraphicspixmapItem representing the loaded image
# Point configuration
self.point_rad = 12 # Radius,in pixels
self.point_pen_color = QtGui.QColor(255, 74, 230) # R,G,B,A
self.point_pen = QtGui.QPen(self.point_pen_color, 6)
self.point_brush_color = QtGui.QColor(195, 20) # R,A
self.point_brush = QtGui.QBrush(self.point_brush_color)
self.point_selected = False
self.selected_point = None
font = QtGui.QFont()
font.setPixelSize(48)
font.setBold(True)
self.label_font = font
self.label_pen_color = QtGui.QColor(0, 0) # R,B
self.label_pen = QtGui.QPen(self.label_pen_color, 2)
self.label_brush_color = QtGui.QColor(255, 255) # R,B
self.label_brush = QtGui.QBrush(self.label_brush_color)
def draw_Box(self, Box, style, num):
x1, y2 = Box.left(), Box.top(), Box.right(), Box.bottom()
x1 = int(x1 * self.i_scale[n])
y1 = int(y1 * self.i_scale[n])
x2 = int(x2 * self.i_scale[n])
y2 = int(y2 * self.i_scale[n])
width = BASEWIDTH
if style == 'match':
width *= 2
painter = QPainter(self.i_pixmap[n])
painter.setPen(QPen(QBrush(color), width))
painter.drawRect(x1, x2 - x1, y2 - y1)
painter.setPen(QPen(QBrush(TEXTCOLOR), TEXTWIDTH))
painter.setFont(TEXTFONT)
painter.drawText(x1, y2 + TEXTSIZE + 2 * BASEWIDTH, '{}: {}'.format(n + 1, num))
painter.end()
self.i_lbl[n].setpixmap(self.i_pixmap[n])
def pen(self, color=Qt.black, style=Qt.SolidLine):
pen = QPen(color)
pen.setStyle(style)
return pen
def _add_latest_input_line(self, angle):
"""Adds a line to the graphic scene that visualizes a scanned angle"""
mx, my = self._get_middle()
angle_rad = deg2rad(angle)
angle_1_rad = deg2rad(angle - self.measurement_angle/2.0)
angle_2_rad = deg2rad(angle + self.measurement_angle/2.0)
length = max(self.width(), self.height())
start_point = (mx, my)
p1 = (mx + length * math.cos(angle_1_rad), my + length * math.sin(angle_1_rad))
p2 = (mx + length * math.cos(angle_2_rad), my + length * math.sin(angle_2_rad))
gradient_start_point, gradient_end_point = (mx, my), (mx + length * math.cos(angle_rad), my + length * math.sin(angle_rad))
gradient = QLinearGradient(*gradient_start_point, *gradient_end_point)
gradient.setColorAt(0, Qt.transparent)
gradient.setColorAt(0.8, Qt.red)
gradient.setColorAt(1, Qt.darkRed)
triangle = QpolygonF()
triangle.append(QPointF(*start_point))
triangle.append(QPointF(*p1))
triangle.append(QPointF(*p2))
triangle.append(QPointF(*start_point))
self.scene.addpolygon(triangle, pen=QPen(Qt.transparent), brush=QBrush(gradient))
def _add_measurement(self, length, angle, added_time):
"""
Adds a visualization for a measured distance to the scene
:param length: length in cm
:param angle: the angle
"""
mx, my = self._get_middle()
angle_rad = deg2rad(angle)
ex, ey = mx + length * math.cos(angle_rad), my + length * math.sin(angle_rad)
age = time.time() - added_time
age = age if age < self.fade_out_time else self.fade_out_time
alpha_channel_value = scale((0, self.fade_out_time), (255, age)
assert 0 <= alpha_channel_value <= 255
brush_color = QColor(self.measured_distances_color)
brush_color.setAlpha(alpha_channel_value)
brush = QBrush(brush_color)
tpen = QPen(brush_color)
self.scene.addLine(mx, ex, ey, pen=tpen)
self.scene.addEllipse(ex-self.dot_width/2, ey-self.dot_width/2, self.dot_width, pen=tpen, brush=brush)
def _add_circles(self, add_text_labels=True):
"""
Adds n circles to the graphic scene.
:param n: the number of circles
"""
pen = QPen(self.circle_line_color)
pen.setStyle(Qt.DotLine)
pen.setWidth(self.line_width)
width, self.height()
stepw, steph = width/n, height/n
mx, my = self._get_middle()
for i in range(1, n+1):
w, h = width - i * stepw, height - i * steph
self.scene.addEllipse((width-w)/2, (height-h)/2, pen)
if add_text_labels:
text = qgraphicstextitem()
text.setDefaultTextColor(self.text_label_color)
text.setPlainText(str(int(w/2)))
text.setPos(mx+w/2.0, my)
text2 = qgraphicstextitem()
text2.setDefaultTextColor(self.text_label_color)
text2.setPlainText(str(int(-w / 2)))
text2.setPos(mx - w / 2.0, my)
self.scene.addItem(text)
self.scene.addItem(text2)
def __init__(self, port, graph, hOffset, connectionPointType):
super(PortCircle, self).__init__(port)
self.__port = port
self._graph = graph
self._connectionPointType = connectionPointType
self.__connections = set()
self._supportsOnlySingleConnections = connectionPointType == 'In'
self.setSizePolicy(QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed))
size = QtCore.QSizef(self.__diameter, self.__diameter)
self.setPreferredSize(size)
self.setwindowFrameMargins(0, 0)
self.transform().translate(self.__radius * hOffset, 0)
self.__defaultPen = QtGui.QPen(QtGui.QColor("#000000"), 1.0)
self.__hoverPen = QtGui.QPen(QtGui.QColor("#000000"), 1.5)
self._ellipseItem = QtWidgets.QGraphicsEllipseItem(self)
self._ellipseItem.setPen(self.__defaultPen)
self._ellipseItem.setPos(size.width()/2, size.height()/2)
self._ellipseItem.setRect(
-self.__radius,
-self.__radius,
self.__diameter,
)
self.setColor(color)
self.setAcceptHoverEvents(True)
def setItem(self, item):
item.setParentItem(self)
self.layout().addItem(item)
# def paint(self,widget):
# super(ItemHolder,0)))
# painter.drawRect(self.windowFrameRect())
def connectionPointType(self):
return self._connectionPointType
# def paint(self,widget):
# super(BasePort,0)))
# painter.drawRect(self.windowFrameRect())
def setText(self, text):
self._titleWidget.setText(text)
# def paint(self,widget):
# super(NodeHeader,100)))
# painter.drawRect(self.windowFrameRect())
def addPort(self, alignment):
layout = self.layout()
layout.addItem(port)
layout.setAlignment(port, alignment)
self.adjustSize()
return port
# def paint(self,widget):
# super(PortList,0)))
# painter.drawRect(self.windowFrameRect())
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。