本文整理汇总了Python中PyQt5.QtWidgets.QGraphicsScene.addLine方法的典型用法代码示例。如果您正苦于以下问题:Python QGraphicsScene.addLine方法的具体用法?Python QGraphicsScene.addLine怎么用?Python QGraphicsScene.addLine使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtWidgets.QGraphicsScene
的用法示例。
在下文中一共展示了QGraphicsScene.addLine方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: BoardGUI
# 需要导入模块: from PyQt5.QtWidgets import QGraphicsScene [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsScene import addLine [as 别名]
class BoardGUI(QWidget):
"""cointain the graphical representation of the Board"""
# ratio of bordersize compared to the size of one base square
borderRatio = 0.8
baseRectRatio = 14/15 # 12/13 for normal ratio but looks weird
stoneScale = 0.46
# siganl
stoneClicked = pyqtSignal(tuple)
def __init__(self, parent, game):
super().__init__()
self.initUI(game)
def initUI(self, game):
self.board = game.currentBoard
self.game = game
self.showCoords = True
self.scene = QGraphicsScene()
# grid containing coordinates for the scene
self.grid = []
self.drawGrid()
# initialize and set layout + view
self.view = QGraphicsView(self.scene)
self.view.setMouseTracking(True)
self.view.setViewportUpdateMode(QGraphicsView.FullViewportUpdate)
self.setMouseTracking(True)
box = QHBoxLayout()
box.addWidget(self.view)
self.setLayout(box)
# stones for all positions are created and listed in self.pos dict
self.createPosition()
self.makeCoords() # has to be called after drawGrid!
def resizeEvent(self, e):
self.view.fitInView(self.view.scene().sceneRect(), Qt.KeepAspectRatio)
def boardWidth(self):
"""returns the max width fitting into widget"""
width = self.contentsRect().width()*0.95
height = self.contentsRect().height()*0.95
return min(width, height*self.baseRectRatio)
def boardHeight(self):
"""returns the max width fitting into widget """
return self.boardWidth()*(1/self.baseRectRatio)
def makeGrid(self):
"""
returns coords [[(x, y)]] for the Grid according
to current window mesures
"""
# set scenesize to window size
self.scene.setSceneRect(0, 0, self.boardWidth(), self.boardHeight())
denom = self.board.size + 2*self.borderRatio
baseWidth = self.boardWidth() / denom
baseHeight = self.boardHeight() / denom
leftOffset = 0.5*baseWidth # (self.contentsRect().width()-self.boardWidth())/2
topOffset = 0 # (self.contentsRect().height()-self.boardHeight())/2
partionWidth = [leftOffset+(self.borderRatio+x)*baseWidth
for x in range(self.board.size)]
partionHeight = [topOffset+(self.borderRatio+x)*baseHeight
for x in range(self.board.size)]
grid = [[(x, y) for x in partionWidth] for y in partionHeight]
self.grid = grid
self.baseWidth = baseWidth
def drawGrid(self):
"""draws the background grid"""
self.makeGrid()
for line in self.grid:
self.scene.addLine(*line[0], *line[-1])
for (pointT, pointB) in zip(self.grid[0], self.grid[-1]):
self.scene.addLine(*pointT, *pointB)
self.drawHoshis()
def makeCoords(self):
""" draws Coordinates """
xLabels = "ABCDEFGHIKLMNOPQRSTUVWXYZ"
yLabels = list(range(1, 26))
botGrid = []
leftGrid = []
# generate pixel coordinates grids
for n in range(self.board.size):
(xBot, yBot) = self.grid[self.board.size-1][n]
yBot += self.baseWidth*0.4/self.baseRectRatio
xBot -= self.baseWidth*0.1
botGrid.append((xBot, yBot))
(xLeft, yLeft) = self.grid[n][0]
xLeft -= self.baseWidth*1.2
#.........这里部分代码省略.........
示例2: CircuitDiagramView
# 需要导入模块: from PyQt5.QtWidgets import QGraphicsScene [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsScene import addLine [as 别名]
#.........这里部分代码省略.........
else:
return (int((x - self.startingX) / self.blockSideLength), int((y - self.startingY) / self.blockSideLength))
def blockIndexToCoordinate(self, x, y):
return (self.startingX + self.blockSideLength * x, self.startingY + self.blockSideLength * y)
def mousePressEvent(self, event):
index = self.mouseCoordinatesToBlockIndex(event.x(), event.y())
self.mousePress.emit(index, (event.x(), event.y()))
def dragEnterEvent(self, event):
event.acceptProposedAction()
def dragMoveEvent(self, event):
index = self.mouseCoordinatesToBlockIndex(event.pos().x(), event.pos().y())
self.mouseMove.emit(index, (event.pos().x(), event.pos().y()))
def dropEvent(self, event):
event.acceptProposedAction()
index = self.mouseCoordinatesToBlockIndex(event.pos().x(), event.pos().y())
self.mouseRelease.emit(index, (event.pos().x(), event.pos().y()))
def mouseMoveEvent(self, event):
self.mousePosition = (event.x(), event.y())
if self.dragging:
self.render()
index = self.mouseCoordinatesToBlockIndex(event.x(), event.y())
self.mouseMove.emit(index, (event.pos().x(), event.pos().y()))
def mouseReleaseEvent(self, event):
index = self.mouseCoordinatesToBlockIndex(event.x(), event.y())
self.mouseRelease.emit(index, (event.pos().x(), event.pos().y()))
def resizeEvent(self, event):
self.render()
def render(self):
if self.model is not None:
self.scene.clear()
self.renderCircuitDiagramGrid()
self.renderComponents()
def renderComponents(self):
if self.model is not None:
for component in self.model.components:
pixmap = self.componentToImage(component)
pixmapItem = self.scene.addPixmap(pixmap)
offset = self.blockIndexToCoordinate(component.position[0],component.position[1])
pixmapItem.setOffset(offset[0],offset[1])
pixmapItem.setTransformationMode(Qt.SmoothTransformation)
if component is self.selection:
if self.dragging:
renderPosition = (self.startingX + self.selection.position[0] * self.blockSideLength + self.mousePosition[0] - self.draggingStart[0], self.startingY + self.selection.position[1] * self.blockSideLength + self.mousePosition[1] - self.draggingStart[1])
pixmapItem.setOffset(renderPosition[0], renderPosition[1])
elif self.shouldShowSelection:
pen = QPen(QBrush(QColor(0,0,255,100)), 2, Qt.DashLine)
self.scene.addRect(self.startingX + component.position[0] * self.blockSideLength, self.startingY + component.position[1] * self.blockSideLength, self.blockSideLength, self.blockSideLength, pen)
if component.type is ComponentType.Ammeter:
font = QFont("Arial", self.blockSideLength/3.5)
reading = self.scene.addText(str("%.2f" % component.current) + "A", font)
offset = self.blockIndexToCoordinate(component.position[0],component.position[1])
reading.setPos(offset[0]+self.blockSideLength/20,offset[1]+self.blockSideLength/4)
elif component.type is ComponentType.Voltmeter:
font = QFont("Arial", self.blockSideLength/3.5)
reading = self.scene.addText(str("%.2f" % component.voltage) + "V", font)
offset = self.blockIndexToCoordinate(component.position[0],component.position[1])
reading.setPos(offset[0]+self.blockSideLength/20,offset[1]+self.blockSideLength/4)
def renderCircuitDiagramGrid(self):
pen = QPen(QBrush(QColor(200,200,200,255)), 1)
pen2 = QPen(QBrush(QColor(100,100,100,255)), 3)
width = self.width()
height = self.height()
self.blockSideLength = width / (self.model.gridSize + 2) if width < height else height / (self.model.gridSize + 2)
# draw vertical lines
currentX = width / 2
self.startingX = currentX - (self.model.gridSize / 2) * self.blockSideLength
while currentX - self.blockSideLength >= 0:
currentX -= self.blockSideLength
while currentX < width:
self.scene.addLine(currentX, 1, currentX, height - 1, pen)
currentX += self.blockSideLength
# draw horizontal lines
currentY = height / 2
self.startingY = currentY - (self.model.gridSize / 2) * self.blockSideLength
while currentY - self.blockSideLength >= 0:
currentY -= self.blockSideLength
while currentY < height:
self.scene.addLine(1, currentY, width - 1, currentY, pen)
currentY += self.blockSideLength
self.scene.addLine(self.startingX, self.startingY, self.startingX + self.model.gridSize * self.blockSideLength, self.startingY, pen2)
self.scene.addLine(self.startingX, self.startingY + self.model.gridSize * self.blockSideLength, self.startingX + self.model.gridSize * self.blockSideLength, self.startingY + 10 * self.blockSideLength, pen2)
self.scene.addLine(self.startingX, self.startingY, self.startingX, self.startingY + self.model.gridSize * self.blockSideLength, pen2)
self.scene.addLine(self.startingX + self.model.gridSize * self.blockSideLength, self.startingY, self.startingX + self.model.gridSize * self.blockSideLength, self.startingY + 10 * self.blockSideLength, pen2)
示例3: Spectrum
# 需要导入模块: from PyQt5.QtWidgets import QGraphicsScene [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsScene import addLine [as 别名]
#.........这里部分代码省略.........
data : ndarray
1D vector containing the data only
This function can be called by self.display_window (which reads the
data for the selected channel) or by the mouse-events functions in
traces (which read chunks of data from the user-made selection).
"""
value = self.config.value
self.scene = QGraphicsScene(value['x_min'], value['y_min'],
value['x_max'] - value['x_min'],
value['y_max'] - value['y_min'])
self.idx_fig.setScene(self.scene)
self.add_grid()
self.resizeEvent(None)
s_freq = self.parent.traces.data.s_freq
f, Pxx = welch(data, fs=s_freq,
nperseg=int(min((s_freq, len(data))))) # force int
freq_limit = (value['x_min'] <= f) & (f <= value['x_max'])
if self.config.value['log']:
Pxx_to_plot = log(Pxx[freq_limit])
else:
Pxx_to_plot = Pxx[freq_limit]
self.scene.addPath(Path(f[freq_limit], Pxx_to_plot),
QPen(QColor(LINE_COLOR), LINE_WIDTH))
def add_grid(self):
"""Add axis and ticks to figure.
Notes
-----
I know that visvis and pyqtgraphs can do this in much simpler way, but
those packages create too large a padding around the figure and this is
pretty fast.
"""
value = self.config.value
# X-AXIS
# x-bottom
self.scene.addLine(value['x_min'], value['y_min'],
value['x_min'], value['y_max'],
QPen(QColor(LINE_COLOR), LINE_WIDTH))
# at y = 0, dashed
self.scene.addLine(value['x_min'], 0,
value['x_max'], 0,
QPen(QColor(LINE_COLOR), LINE_WIDTH, Qt.DashLine))
# ticks on y-axis
y_high = int(floor(value['y_max']))
y_low = int(ceil(value['y_min']))
x_length = (value['x_max'] - value['x_min']) / value['x_tick']
for y in range(y_low, y_high):
self.scene.addLine(value['x_min'], y,
value['x_min'] + x_length, y,
QPen(QColor(LINE_COLOR), LINE_WIDTH))
# Y-AXIS
# left axis
self.scene.addLine(value['x_min'], value['y_min'],
value['x_max'], value['y_min'],
QPen(QColor(LINE_COLOR), LINE_WIDTH))
# larger ticks on x-axis every 10 Hz
x_high = int(floor(value['x_max']))
x_low = int(ceil(value['x_min']))
y_length = (value['y_max'] - value['y_min']) / value['y_tick']
for x in range(x_low, x_high, 10):
self.scene.addLine(x, value['y_min'],
x, value['y_min'] + y_length,
QPen(QColor(LINE_COLOR), LINE_WIDTH))
# smaller ticks on x-axis every 10 Hz
y_length = (value['y_max'] - value['y_min']) / value['y_tick'] / 2
for x in range(x_low, x_high, 5):
self.scene.addLine(x, value['y_min'],
x, value['y_min'] + y_length,
QPen(QColor(LINE_COLOR), LINE_WIDTH))
def resizeEvent(self, event):
"""Fit the whole scene in view.
Parameters
----------
event : instance of Qt.Event
not important
"""
value = self.config.value
self.idx_fig.fitInView(value['x_min'],
value['y_min'],
value['x_max'] - value['x_min'],
value['y_max'] - value['y_min'])
def reset(self):
"""Reset widget as new"""
self.idx_chan.clear()
if self.scene is not None:
self.scene.clear()
self.scene = None
示例4: AMANDisplay
# 需要导入模块: from PyQt5.QtWidgets import QGraphicsScene [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsScene import addLine [as 别名]
class AMANDisplay(QGraphicsView):
def __init__(self):
super(AMANDisplay, self).__init__()
self.setGeometry(0, 0, 500, 600)
self.setStyleSheet("background-color:#233370")
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.scene = QGraphicsScene(0, 0, 500, 600)
# Timeline boundaries
pen = QPen(QColor("white"))
brush = QBrush(QColor("#233370"))
self.scene.addLine(220, 0, 220, 600, pen)
self.scene.addLine(280, 0, 280, 600, pen)
self.scene.addLine(0, 30, 500, 30, pen)
timelinebox = self.scene.addRect(220, 30, 60, 540, pen, brush)
timelinebox.setFlag(timelinebox.ItemClipsChildrenToShape, True)
# Timeline scale
self.timeline = QGraphicsItemGroup()
self.timeline.setParentItem(timelinebox)
self.timeticks = []
for i in range(40):
y = 15 * i
w = 6
if i % 5 == 0:
w = 10
self.timeticks.append(self.scene.addText("%02d" % (40 - i), QFont("Courier", 10)))
self.timeticks[-1].setPos(240, y - 10)
self.timeticks[-1].setDefaultTextColor(QColor("white"))
self.timeline.addToGroup(self.timeticks[-1])
self.timeline.addToGroup(self.scene.addLine(220, y, 220 + w, y, pen))
self.timeline.addToGroup(self.scene.addLine(280 - w, y, 280, y, pen))
self.lrwy = self.scene.addText("18R", QFont("Arial", 20, 50))
self.lrwy.setPos(1, 1)
self.lrwy.setDefaultTextColor(QColor("white"))
# Finalize
self.setScene(self.scene)
self.show()
def update(self, simt, data):
# data has: ids, iafs, eats, etas, delays, rwys, spdratios
# First delete old labels
for (key,) in self.aircraft.keys:
if key not in data.ids:
# del label
del self.aircraft[key]
for i in len(data.ids):
if data.ids[i] not in self.aircraft:
# self.aircraft[data.ids[i]] = QLabel()
pass
# Generate the new label text and position
newtext = "<font color=Red>bla</font>" # veranderen
lbl = self.aircraft[data.ids[i]]
lbl.setText(newtext)
lbl.move(posx, posy) # move in pixels
示例5: InitialPoseDialog
# 需要导入模块: from PyQt5.QtWidgets import QGraphicsScene [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsScene import addLine [as 别名]
class InitialPoseDialog(QDialog, Ui_PoseDialog):
data_manager = None
image = None
y_line = 0
y_top_line = 0
y_lower_line = 0
landmark_size = 2
lines = None
middle_idx = 0
pose_model = None
def __init__(self, data_manager):
super(InitialPoseDialog, self).__init__()
self.setupUi(self)
self.setAttribute(Qt.WA_DeleteOnClose)
assert isinstance(data_manager, DataManager)
self.data_manager = data_manager
self.pose_model = InitialPoseModel(data_manager)
self.scene = QGraphicsScene()
self.graphicsView.setScene(self.scene)
self.image = Filter.crop_image(self.data_manager.radiographs[0].image)
self.findButton.clicked.connect(self.find_jaw_divider)
self.openButton.clicked.connect(self._open_radiograph)
self._redraw()
def find_jaw_divider(self):
self.y_top_line, self.y_lower_line = self.pose_model._find_jaw_separation_line(self.pose_model._crop_image_sides(self.image))
upper_jaw_image = self.pose_model.crop_upper_jaw(self.image, self.y_top_line)
lower_jaw_image = self.pose_model.crop_lower_jaw(self.image, self.y_lower_line)
# Filter the image
upper_jaw_image = Filter.process_image(upper_jaw_image, median_kernel=5, bilateral_kernel=17, bilateral_color=6)
lower_jaw_image = Filter.process_image(lower_jaw_image, median_kernel=5, bilateral_kernel=17, bilateral_color=6)
upper_jaw_image = self.pose_model._convert_to_binary_image(upper_jaw_image)
lower_jaw_image = self.pose_model._convert_to_binary_image(lower_jaw_image)
upper_lines = self.pose_model._find_hough_lines(upper_jaw_image, threshold=15)
lower_lines = self.pose_model._find_hough_lines(lower_jaw_image, threshold=15)
# Filter out lines
upper_lines = self.pose_model._filter_lines(upper_lines, upper_jaw_image.shape, line_offset=6, max_line_gap=90)
lower_lines = self.pose_model._filter_lines(lower_lines, lower_jaw_image.shape, line_offset=2, max_line_gap=60)
self.image = lower_jaw_image
self.lines = lower_lines
self._redraw()
def _open_radiograph(self):
file_dialog = QFileDialog(self)
file_dialog.setDirectory("./data/Radiographs")
file_dialog.setFileMode(QFileDialog.ExistingFile)
file_dialog.setNameFilter("Radiograph (*.tif)")
if file_dialog.exec_() and len(file_dialog.selectedFiles()) == 1:
radiograph = Radiograph()
radiograph.path_to_img = file_dialog.selectedFiles()[0]
#self.image = radiograph.image
#crop_translation = -Filter.get_cropping_region(radiograph.image).left_top
self.image = Filter.crop_image(radiograph.image)
self.lines = None
self._redraw()
def _redraw(self, normalize=False):
self.scene.clear()
img = self.image.copy()
if normalize:
img = (img / img.max()) * 255
# Draw image
qimg = toQImage(img.astype(np.uint8))
self.scene.addPixmap(QPixmap.fromImage(qimg))
# Add jaws divider
self.scene.addLine(QLineF(0, self.y_line, self.image.shape[1], self.y_line), pen=QPen(QColor.fromRgb(255, 0, 0)))
self.scene.addLine(QLineF(0, self.y_top_line, self.image.shape[1], self.y_top_line), pen=QPen(QColor.fromRgb(255, 0, 0)))
self.scene.addLine(QLineF(0, self.y_lower_line, self.image.shape[1], self.y_lower_line), pen=QPen(QColor.fromRgb(255, 0, 0)))
# Add image center
self.scene.addEllipse(self.image.shape[0]/2 - self.landmark_size, self.image.shape[1]/2 - self.landmark_size,
self.landmark_size * 2, self.landmark_size * 2,
pen=QPen(QColor.fromRgb(255, 0, 0)), brush=QBrush(QColor.fromRgb(255, 0, 0)))
# Draw Hough lines
if self.lines is not None:
#for x1,y1,x2,y2 in self.lines[0]:
for i, line_param in enumerate(self.lines):
rho,theta = line_param
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
#.........这里部分代码省略.........
示例6: MapPainter
# 需要导入模块: from PyQt5.QtWidgets import QGraphicsScene [as 别名]
# 或者: from PyQt5.QtWidgets.QGraphicsScene import addLine [as 别名]
class MapPainter(object):
def __init__(self, parent, view, displayCities, displayConnections, displayBestUnit):
super().__init__()
self.view = view
self.displayCities = displayCities
self.displayConnections = displayConnections
self.displayBestUnit = displayBestUnit
self.problemMap = None
self.bestUnit = None
self.scene = QGraphicsScene(parent)
self.resizeScene()
self.view.setScene(self.scene)
self.view.fitInView(self.scene.sceneRect(), Qt.KeepAspectRatio)
def resizeScene(self):
height = self.view.size().height()
width = self.view.size().width()
self.scene.setSceneRect(0.0, 0.0, width, height)
def setProblemMap(self, problemMap):
self.problemMap = problemMap
def setBestUnit(self, unit):
self.bestUnit = unit
def setDisplayCities(self, enabled = False):
self.displayCities = bool(enabled)
def setDisplayConnections(self, enabled = False):
self.displayConnections = bool(enabled)
def setDisplayBestUnit(self, enabled = False):
self.displayBestUnit = bool(enabled)
def repaint(self):
if self.problemMap is None:
return
self.scene.clear()
self.resizeScene()
height = self.scene.height()
width = self.scene.width()
if self.displayCities:
cityBrush = QBrush(QColor(0, 0, 0), Qt.SolidPattern)
cityPen = QPen(cityBrush, 5.0)
for city in self.problemMap.cities:
x = width * city.positionX
y = height * city.positionY
self.scene.addEllipse(x, y, 4, 4, cityPen, cityBrush)
if self.displayConnections:
connectionBrush = QBrush(QColor(0, 0, 255), Qt.SolidPattern)
connectionPen = QPen(connectionBrush, 1.0)
for city in self.problemMap.cities:
for neighbour in city.connections:
x = width * city.positionX
y = height * city.positionY
x2 = width * self.problemMap.cities[neighbour].positionX
y2 = height * self.problemMap.cities[neighbour].positionY
self.scene.addLine(x, y, x2, y2, connectionPen)
if self.displayBestUnit and self.bestUnit is not None:
bestUnitBrush = QBrush(QColor(255, 0, 0), Qt.SolidPattern)
bestUnitPen = QPen(bestUnitBrush, 2.0)
for i in range(-1, len(self.bestUnit.path)-1):
currCity = self.problemMap.cities[self.bestUnit.path[i]]
nextCity = self.problemMap.cities[self.bestUnit.path[i+1]]
x = width * currCity.positionX
y = height * currCity.positionY
x2 = width * nextCity.positionX
y2 = height * nextCity.positionY
self.scene.addLine(x, y, x2, y2, bestUnitPen)
self.view.fitInView(self.scene.sceneRect())