def add_signals(self): self.signals_group_text = QtWidgets.QGraphicsItemGroup() self.signals_group_arrow = QtWidgets.QGraphicsItemGroup() self.signals_text_items = np.empty(len(Quotes), dtype=object) for p in Portfolio.positions: x, price = p.id_bar_open, p.open_price if p.type == Order.BUY: y = Quotes[x].low * 0.99 pg.ArrowItem( parent=self.signals_group_arrow, pos=(x, y), pen=self.plotgroup.long_pen, brush=self.plotgroup.long_brush, angle=90, headLen=12, tipAngle=50, ) text_sig = CenteredTextItem( parent=self.signals_group_text, pos=(x, y), pen=self.plotgroup.long_pen, brush=self.plotgroup.long_brush, text=('Buy at {:.%df}' % self.plotgroup.digits).format(price), valign=QtCore.Qt.AlignBottom, ) text_sig.hide() else: y = Quotes[x].high * 1.01 pg.ArrowItem( parent=self.signals_group_arrow, pos=(x, y), pen=self.plotgroup.short_pen, brush=self.plotgroup.short_brush, angle=-90, headLen=12, tipAngle=50, ) text_sig = CenteredTextItem( parent=self.signals_group_text, pos=(x, y), pen=self.plotgroup.short_pen, brush=self.plotgroup.short_brush, text=('Sell at {:.%df}' % self.plotgroup.digits).format(price), valign=QtCore.Qt.AlignTop, ) text_sig.hide() self.signals_text_items[x] = text_sig self.chart.addItem(self.signals_group_arrow) self.chart.addItem(self.signals_group_text) self.signals_visible = True
def draw_interface(self, view, scene, tree, points): """ Функция, отрисовывающая начальный вид интерфейса с помощью PyQt """ # Очищаем сцену для рисования новых элементов scene.clear() view.setScene(scene) view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # Добавление границ каждой сцене, чтобы GraphicsView не пытался размещать по центру элементы scene.addLine(0, 0, view.width(), 0, QPen(QColor(255, 255, 255))) scene.addLine(view.width(), 0, view.width(), view.height(), QPen(QColor(255, 255, 255))) scene.addLine(view.width(), view.height(), 0, view.height(), QPen(QColor(255, 255, 255))) scene.addLine(0, view.height(), 0, 0, QPen(QColor(255, 255, 255))) # Создаём графическме группы для раздельного отображения схемы расположения элементов и тепловой карты if view == self.ui.initialView: self.initial_tree_group = QtWidgets.QGraphicsItemGroup() self.initial_heatmap_group = QtWidgets.QGraphicsItemGroup() tree_group = self.initial_tree_group heatmap_group = self.initial_heatmap_group else: self.optimized_tree_group = QtWidgets.QGraphicsItemGroup() self.optimized_heatmap_group = QtWidgets.QGraphicsItemGroup() tree_group = self.optimized_tree_group heatmap_group = self.optimized_heatmap_group # Определяем коэффициенты пропорциональности размеров элементов дерева и размеров на форме (2px = границы) if scene == self.initial_scene: self.initial_scale_x = tree.root.width / (view.width() - 2) self.initial_scale_y = tree.root.height / (view.height() - 2) scale_x = self.initial_scale_x scale_y = self.initial_scale_y else: self.optimized_scale_x = tree.root.width / (view.width() - 2) self.optimized_scale_y = tree.root.height / (view.height() - 2) scale_x = self.optimized_scale_x scale_y = self.optimized_scale_y # Заполняем созданные графические группы элементами и тепловыми картами соответственно points.clear() self.fill_tree_group(tree, tree.root, tree_group, points, scale_x, scale_y) self.fill_heatmap_group(view, points, heatmap_group) # Добавляем на сцены соответственные группы элементов и теповых карт scene.addItem(tree_group) scene.addItem(heatmap_group)
def plot(self): """ create grafiks group item with all grafik pyqt elements of the player """ self.item_group = QtWidgets.QGraphicsItemGroup() #for i in range(1,len(self._line_list)): # # -> mulitplay pos with line with -> move to upper field corner # p1 = self._line_list[i-1] # p2 = self._line_list[i] # l = QtWidgets.QGraphicsLineItem() # l.setLine(p1.x()*self.magnification,p1.y()*self.magnification,p2.x()*self.magnification,p2.y()*self.magnification) # l.setPen(self.pen) # self.item_group.addToGroup(l) for l in self._line_list: ql = l.get_q_line_item() ql.setPen(self.pen) self.item_group.addToGroup(ql) for i in range(0,len(self._point_list)): # -> mulitplay pos with line with -> move to upper field corner p = self._point_list[i] l = QtWidgets.QGraphicsEllipseItem() l.setRect((p.x()-0.5)*self.magnification,(p.y()-0.5)*self.magnification,self.magnification,self.magnification) #l.setLine(p1.x()*self.magnification,p1.y()*self.magnification,p2.x()*self.magnification,p2.y()*self.magnification) #l.setPen(self.pen) l.setBrush(QtGui.QColor(255,0,0)) self.item_group.addToGroup(l) return self.item_group
def setupScene(self): self.scene = QtWidgets.QGraphicsScene() self.viewwidget.setScene(self.scene) self.cursor = QtWidgets.QGraphicsItemGroup() self.cursor.setZValue(100) circle = QtWidgets.QGraphicsEllipseItem(self.cursor) circle.setRect(-5, -5, 10, 10) circle.setBrush(QtGui.QBrush(QtCore.Qt.red)) circle.setFlag(QtWidgets.QGraphicsItem.ItemIgnoresTransformations, True) self.scene.addItem(self.cursor) def onMouseMoveEvent(event): position = QtCore.QPointF(event.scenePos()) self.xwidget.setText(str(position.x())) self.ywidget.setText(str(position.y())) origin = relative_position_default_origin self.latwidget.setText( str(round(origin[0] + position.y() / (6371000 * deg), 6))) self.lonwidget.setText( str( round( origin[1] + position.x() / math.cos(deg * origin[0] + position.y() / 6371000) / (6371000 * deg), 6))) QtWidgets.QGraphicsScene.mouseMoveEvent( self.scene, event) # propagate to objects in scene self.scene.mouseMoveEvent = onMouseMoveEvent
def draw_origin(self): pen = qg.QPen(qg.QColor('#e533e5'), 2) pen.setCosmetic(True) # changes width depending on zoom pen.setJoinStyle(qc.Qt.RoundJoin) length = self.scene.itemsBoundingRect().width() / 16 diameter = length / 10 origin_item = qw.QGraphicsItemGroup() circle = qw.QGraphicsEllipseItem( qc.QRectF(-diameter / 2, -diameter / 2, diameter, diameter)) circle.setPen(pen) circle.setEnabled(False) origin_item.addToGroup(circle) x_line = qw.QGraphicsLineItem( 0, 0, length, 0, ) x_line.setPen(pen) origin_item.addToGroup(x_line) y_line = qw.QGraphicsLineItem(0, 0, 0, length) y_line.setPen(pen) origin_item.addToGroup(y_line) origin_item.setEnabled(False) origin_item.setZValue(-1) self.scene_origin = origin_item self.scene.addItem(self.scene_origin)
def __init__(self, windows, car): self.t = 0 self.car = car self.windows = windows self.car_group = QtWidgets.QGraphicsItemGroup() self.windows.scene.addItem(self.car_group) self.r = self.car.direction[0] * (180 / math.pi) - 90 transform = QTransform() transform.rotate(self.r) self.car_group.setTransform(transform) self.car_group.setZValue(1) self.path = QtGui.QPainterPath() self.voiture = QRectF( QPoint(self.car.position[0].x - self.car.longueur / 2, self.car.position[0].y - self.car.largeur / 2), QPoint(self.car.position[0].x + self.car.longueur / 2, self.car.position[0].y + self.car.largeur / 2)) # self.voiture = QRectF(QPoint(self.car.position[0].x-self.car.largeur/2, self.car.position[0].y-self.car.longueur/2), QPoint(self.car.position[0].x+self.car.largeur/2, self.car.position[0].y+self.car.longueur/2)) self.path.addRect(self.voiture) brush = QBrush(QtGui.QColor("Red")) item = QtWidgets.QGraphicsPathItem(self.path, self.car_group) item.setBrush(brush) item.setPen(QPen(QtGui.QColor("Red")))
def updateLeavesOutline(self): group = QtWidgets.QGraphicsItemGroup() for lf in self.model.quadtree.leaves: group.addToGroup(QQuadLeaf(lf).getRectItem()) group.setOpacity(0.4) if self.outlined_leaves is not None: self.vb.removeItem(self.outlined_leaves) self.outlined_leaves = group self.vb.addItem(self.outlined_leaves)
def update_interface(self): """ Функция, выполняющая перерисовку сцены после изменения дерева """ # Очищаем сцену группы для рисования новых элементов self.optimized_scene.clear() self.optimized_tree_group = QtWidgets.QGraphicsItemGroup() self.optimized_heatmap_group = QtWidgets.QGraphicsItemGroup() # Заполняем созданные графические группы элементами и тепловыми картами соответственно points = [] self.fill_tree_group(self.optimized_tree, self.optimized_tree.root, self.optimized_tree_group, points, self.optimized_scale_x, self.optimized_scale_y) self.fill_heatmap_group(self.ui.optimizedView, points, self.optimized_heatmap_group) # Добавляем на сцены соответственные группы элементов и теповых карт if self.ui.elementsCheckBox.isChecked(): self.optimized_scene.addItem(self.optimized_tree_group) if self.ui.heatmapCheckBox.isChecked(): self.optimized_scene.addItem(self.optimized_heatmap_group)
def __init__(self, widget: QtWidgets.QWidget = 0): super(GraphicsView, self).__init__() self.setMinimumSize(100, 100) self.setAlignment(QtCore.Qt.AlignCenter) self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.scene = QtWidgets.QGraphicsScene() self.setScene(self.scene) self.group1 = QtWidgets.QGraphicsItemGroup() self.group2 = QtWidgets.QGraphicsItemGroup() self.scene.addItem(self.group1) self.scene.addItem(self.group2) self.timer = QtCore.QTimer() self.timer.setSingleShot(True) self.timer.start(50) self.timer.timeout.connect(self.slotAlarmTimer)
def add_trajectory_items(self, flights): trajectory_group = QtWidgets.QGraphicsItemGroup() flight_group = QtWidgets.QGraphicsItemGroup() self.scene.addItem(trajectory_group) self.scene.addItem(flight_group) # Trajectories and starting points pen = QPen(QtGui.QColor(TRAJECTORY_COLOR), TRAJECTORY_WIDTH) pen.setCapStyle(QtCore.Qt.RoundCap) pen.setJoinStyle(QtCore.Qt.MiterJoin) for f in flights: path = QtGui.QPainterPath() trajectory = f.completeTrajectory(N_POINT_TRAJECTORY) path.moveTo(trajectory[0].x(), trajectory[0].y()) for xy in trajectory[1:]: path.lineTo(xy.x(), xy.y()) item = QtWidgets.QGraphicsPathItem(path, trajectory_group) item.setPen(pen) # item.setToolTip('Trajectoire ' + 'trajectory.name') item2 = AircraftItem(f) flight_group.addToGroup(item2)
def add_airport_items(self): """ Adds the airport (as a group) to the QGraphicsScene, drawn by the view""" airport_group = QtWidgets.QGraphicsItemGroup() self.scene.addItem(airport_group) airport_group.setZValue(AIRPORT_Z_VALUE) apt = self.simulation.airport # Taxiways pen = QPen(QtGui.QColor(APT_COLOR), airport.TAXIWAY_WIDTH) pen.setCapStyle(QtCore.Qt.RoundCap) for taxiway in apt.taxiways: path = QtGui.QPainterPath() path.moveTo(taxiway.coords[0].x, taxiway.coords[0].y) for xy in taxiway.coords[1:]: path.lineTo(xy.x, xy.y) item = QtWidgets.QGraphicsPathItem(path, airport_group) item.setPen(pen) item.setToolTip('Taxiway ' + taxiway.taxi_name) # Runways pen = QPen(QtGui.QColor(APT_COLOR), airport.RUNWAY_WIDTH) for runway in apt.runways: (p1, p2) = runway.coords item = QtWidgets.QGraphicsLineItem(p1.x, p1.y, p2.x, p2.y, airport_group) item.setPen(pen) item.setToolTip('Runway ' + runway.name) # Named points pen = QPen(QtCore.Qt.transparent) width = 0.7 * traffic.SEP dw = width / 2. for point in apt.points: bounds = QtCore.QRectF(point.x - dw, point.y - dw, width, width) if point.type == airport.PointType.STAND: item = QtWidgets.QGraphicsEllipseItem(bounds, airport_group) item.setBrush(STAND_BRUSH) point_type_description = "Stand" else: item = QtWidgets.QGraphicsRectItem(bounds, airport_group) item.setBrush(POINT_BRUSH) if point.type == airport.PointType.RUNWAY_POINT: point_type_description = "Runway point" else: point_type_description = "Deicing point" item.setPen(pen) item.setToolTip(point_type_description + ' ' + point.name)
def add_piste(self): #création des éléments de la piste track_group = QtWidgets.QGraphicsItemGroup() self.scene.addItem(track_group) pen = QPen(QtGui.QColor(TK_COLOR), LARGEUR) pen.setJoinStyle(Qt.RoundJoin) self.extrem(4) path = QtGui.QPainterPath() path.moveTo(self.piste[0].x, self.piste[0].y) for i in range(1, len(self.piste)): path.lineTo(self.piste[i].x, self.piste[i].y) item = QtWidgets.QGraphicsPathItem(path, track_group) item.setPen(pen)
def __init__(self, size=0.05, linewidth=0.01, color='#333333'): qitem = QtWidgets.QGraphicsItemGroup() self._lh = Line(-size / 2, 0, size / 2, 0, width=linewidth, color=color) self._lv = Line(0, -size / 2, 0, size / 2, width=linewidth, color=color) qitem.addToGroup(self._lh.qitem) qitem.addToGroup(self._lv.qitem) super(Cross, self).__init__(qitem)
def __init__(self, symbol, parent=None): super().__init__(parent) self._symbol = symbol try: renderer, svg_symbol = self._cache[self._symbol] except KeyError: path = os.path.join(DATA_DIR, 'symbols', '%s.svg' % self._symbol) svg_symbol = SvgSymbol(path) renderer = QtSvg.QSvgRenderer(svg_symbol.get_xml()) self._cache[self._symbol] = (renderer, svg_symbol) self.grp = QtWidgets.QGraphicsItemGroup(self) origin_x, origin_y = svg_symbol.get_origin() self.grp.setPos(-origin_x, -origin_y) self.body = QtSvg.QGraphicsSvgItem(self.grp) self.body.setSharedRenderer(renderer)
def __init__(self, parent): super(PhotoViewer, self).__init__(parent) self._zoom = 0 self._empty = True self._scene = QtWidgets.QGraphicsScene(self) self._photo = QtWidgets.QGraphicsPixmapItem() self._scene.addItem(self._photo) self.setScene(self._scene) self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse) self.setResizeAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse) self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) self.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(30, 30, 30))) self.setFrameShape(QtWidgets.QFrame.NoFrame) self.highlight = QtWidgets.QGraphicsRectItem() self._scene.addItem(self.highlight) self.annotation_items = QtWidgets.QGraphicsItemGroup()
def __init__(self): self.name = "" self._line_list = [] self._point_list = [] self.type = "" self.item_group = QtWidgets.QGraphicsItemGroup() self.raster_size = 1 self.magnification=10 # -> muss über eine property gemacht werden self.pen = QtGui.QPen() self.pen.setWidth(self.magnification) self.color = '#000000' self.status_remove = False
def initialize_tiles(self,nbs,nba,ac,cursor,click): for item in self.my_scene.items(): self.my_scene.removeItem(item) self._mouseIsPressed = False self._mouseIsMoved = False self.max_zoom_factor = 20 self._zoom = 0 self._empty = False self.cursor_selection = cursor self.click_function = click self.wedges = {} self.chosen_wedge_indices = set() self.edited_wedges_indices = set() self._a = 800/2**nbs self._tiles_size = 2**nbs*self._a + 200 self.nbs = nbs self.nba = nba self.ac = ac self._photo = QtWidgets.QGraphicsPixmapItem() self._background = QtGui.QPixmap(self._tiles_size,self._tiles_size) self._background.fill(QtGui.QColor("white")) self._photo.setPixmap(self._background) self._item_group = QtWidgets.QGraphicsItemGroup() self._labelText = QtWidgets.QGraphicsTextItem("") self._labelText.setDefaultTextColor(QtGui.QColor("black")) self._labelText.setPlainText("Number of scales = {}\nNumber of angles = {}".format(self.nbs, self.nba)) self._labelText.setPos(40,40) self._labelText.setFlag(QtWidgets.QGraphicsItem.ItemIgnoresTransformations,True) self._labelText.show() self._labelIsPresent = True self._item_group.addToGroup(self._labelText) self.my_scene.addItem(self._item_group) self.my_scene.addItem(self._photo) self._is_initialized = True for i in range(nbs): m = 1 if i == 0 else self.nba * 2**(i//2) available = False if not self.ac and i == nbs-1 else True for j in range(m): self.add_wedge(i,j,available)
def drawMarker(self, coords, pen, brush=None, ref=None): """Draws a feature marker on the main view. Returns an object reference. Args: coords (tuple): A 2-tuple of ints (x, y) where x and y are the midpoint coordinates of the marker. pen (QtGui.QPen): Pen to use for drawing the object. brush (QtGui.QBrush): Brush to use for drawing the object. ref (object): Reference an existing object to update here, or None to create a new object. Returns: QGraphicsItem: Reference to the graphical object. """ scene = self.scene() x, y = coords w, h = (10, 10) if ref is None: ref = QtWidgets.QGraphicsItemGroup() hline = QtWidgets.QGraphicsLineItem(0, int(h/2), w, int(h/2)) hline.setPen(pen) ref.addToGroup(hline) vline = QtWidgets.QGraphicsLineItem(int(w/2), 0, int(w/2), h) vline.setPen(pen) ref.addToGroup(vline) scene.addItem(ref) else: for c in ref.childItems(): c.setPen(pen) ref.setPos(int(x - w/2), int(y - h/2)) return ref
def __init__(self, stations, powers, main, year=None): super(Visualise, self).__init__() self.year = year self.stations = stations self.powers = powers self.scene = main.view.scene() self.save_View = main.save_View self.viewPrefix = None self.viewSuffix = None self.viewDo = False self.visual_group = QtWidgets.QGraphicsItemGroup() self.visual_items = [] self.scene.addItem(self.visual_group) self.be_open = True self.ignore = False self.detail = ['Diurnal', 'Hourly'] self.the_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] self.mth_index = [0] for i in range(len(self.the_days) - 1): self.mth_index.append(self.mth_index[-1] + self.the_days[i] * 24) config = configparser.RawConfigParser() if len(sys.argv) > 1: config_file = sys.argv[1] else: config_file = getModelFile('SIREN.ini') config.read(config_file) if self.year is None: try: self.year = config.get('Base', 'year') except: pass self.seasons = [] self.periods = [] self.daily = True try: items = config.items('Power') for item, value in items: if item[:6] == 'season': if item == 'season': continue i = int(item[6:]) - 1 if i >= len(self.seasons): self.seasons.append([]) self.seasons[i] = value.split(',') for j in range(1, len(self.seasons[i])): self.seasons[i][j] = int(self.seasons[i][j]) - 1 elif item[:6] == 'period': if item == 'period': continue i = int(item[6:]) - 1 if i >= len(self.periods): self.periods.append([]) self.periods[i] = value.split(',') for j in range(1, len(self.periods[i])): self.periods[i][j] = int(self.periods[i][j]) - 1 elif item == 'save_view': if value.lower() in ['true', 'yes', 'on']: self.viewDo = True except: pass if len(self.seasons) == 0: self.seasons = [['Summer', 11, 0, 1], ['Autumn', 2, 3, 4], ['Winter', 5, 6, 7], ['Spring', 8, 9, 10]] if len(self.periods) == 0: self.periods = [['Winter', 4, 5, 6, 7, 8, 9], ['Summer', 10, 11, 0, 1, 2, 3]] for i in range(len(self.periods)): for j in range(len(self.seasons)): if self.periods[i][0] == self.seasons[j][0]: self.periods[i][0] += '2' break self.stn_items = [] for i in range(len(self.stations)): self.stn_items.append(-1) for i in range(len(self.scene._stations.stations)): try: j = self.stations.index(self.scene._stations.stations[i].name) self.stn_items[j] = i except: pass self.grid = QtWidgets.QGridLayout() row = 0 self.detailCombo = QtWidgets.QComboBox() self.dayCombo = QtWidgets.QComboBox() self.hourCombo = QtWidgets.QComboBox() for det in self.detail: self.detailCombo.addItem(det) self.grid.addWidget(QtWidgets.QLabel('Detail:'), row, 0) self.grid.addWidget(self.detailCombo, row, 1, 1, 2) self.detailCombo.currentIndexChanged[str].connect(self.changeDetail) row += 1 self.grid.addWidget(QtWidgets.QLabel('Period:'), row, 0) self.periodCombo = QtWidgets.QComboBox() self.grid.addWidget(self.periodCombo, row, 1) #, 1, 2) self.grid.addWidget(self.dayCombo, row, 2) #, 1, 2) self.grid.addWidget(self.hourCombo, row, 3) row += 1 prev = QtWidgets.QPushButton('<', self) width = prev.fontMetrics().boundingRect('<').width() + 10 prev.setMaximumWidth(width) self.grid.addWidget(prev, row, 0) prev.clicked.connect(self.prevClicked) self.slider = QtWidgets.QSlider(QtCore.Qt.Horizontal) self.slider.valueChanged.connect(self.slideChanged) self.grid.addWidget(self.slider, row, 1, 1, 5) nextt = QtWidgets.QPushButton('>', self) width = nextt.fontMetrics().boundingRect('>').width() + 10 nextt.setMaximumWidth(width) self.grid.addWidget(nextt, row, 7) nextt.clicked.connect(self.nextClicked) row += 1 self.viewSpin = QtWidgets.QSpinBox() self.viewSpin.setRange(0, 8760) self.viewSpin.setValue(0) if self.viewDo: self.grid.addWidget(QtWidgets.QLabel('Save Views:'), row, 0) self.viewSpin.valueChanged.connect(self.viewChanged) self.grid.addWidget(self.viewSpin, row, 1) row += 1 self.grid.addWidget(QtWidgets.QLabel('Repeat Loop:'), row, 0) self.repeat = QtWidgets.QCheckBox() self.repeat.setCheckState(QtCore.Qt.Unchecked) self.grid.addWidget(self.repeat, row, 1) row += 1 self.do_loop = False self.grid.addWidget(QtWidgets.QLabel('Period Loop (secs):'), row, 0) self.loopSpin = QtWidgets.QDoubleSpinBox() self.loopSpin.setRange(0., 10.) self.loopSpin.setDecimals(2) self.loopSpin.setSingleStep(.05) self.loopSpin.setValue(0.) self.loopSpin.valueChanged[str].connect(self.loopChanged) self.grid.addWidget(self.loopSpin, row, 1, 1, 2) self.loop = QtWidgets.QPushButton('Loop', self) self.grid.addWidget(self.loop, row, 3, 1, 4) self.loop.clicked.connect(self.loopClicked) row += 1 quit = QtWidgets.QPushButton('Quit', self) self.grid.addWidget(quit, row, 0) quit.clicked.connect(self.quitClicked) QtWidgets.QShortcut(QtGui.QKeySequence('q'), self, self.quitClicked) frame = QtWidgets.QFrame() frame.setLayout(self.grid) self.scroll = QtWidgets.QScrollArea() self.scroll.setWidgetResizable(True) self.scroll.setWidget(frame) self.layout = QtWidgets.QVBoxLayout(self) self.layout.addWidget(self.scroll) self.setWindowTitle('SIREN - Visualise generation') self.setWindowIcon(QtGui.QIcon('sen_icon32.ico')) if sys.platform == 'win32' or sys.platform == 'cygwin': move_right = False else: move_right = True QtWidgets.QShortcut(QtGui.QKeySequence('pgup'), self, self.prevClicked) QtWidgets.QShortcut(QtGui.QKeySequence('pgdown'), self, self.nextClicked) QtWidgets.QShortcut(QtGui.QKeySequence('Ctrl++'), self, self.nextClicked) QtWidgets.QShortcut(QtGui.QKeySequence('Ctrl+-'), self, self.prevClicked) QtWidgets.QShortcut(QtGui.QKeySequence('Ctrl+Z'), self, self.loopClicked) self.setPeriod() self.periodCombo.currentIndexChanged[str].connect(self.periodChange) self.dayCombo.currentIndexChanged[str].connect(self.periodChange) self.hourCombo.currentIndexChanged[str].connect(self.periodChange) self.showPeriod(0) self.show()
def add_sequencer_items(self): seq_group = QtWidgets.QGraphicsItemGroup() self.scene.addItem(seq_group) Blanches = ['Do', 'Re', 'Mi', 'Fa', 'Sol', 'La', 'Si'] #Notes blanches pen = QPen(QtGui.QColor("white")) for i in range(49): item = QtWidgets.QGraphicsRectItem(-2 * 1.5, 2 * i + 0.5, 2.5, 1, seq_group) item.setPen(pen) item.setToolTip(Blanches[i % 7]) #Notes noires pen = QPen(QtGui.QColor("black")) for i in range(7): item = QtWidgets.QGraphicsRectItem(-2 * 2, 2 * (7 * i + 1), 2.5, 0, seq_group) item.setPen(pen) item.setToolTip("Do#") item = QtWidgets.QGraphicsRectItem(-2 * 2, 2 * (7 * i + 2), 2.5, 0, seq_group) item.setPen(pen) item.setToolTip("Re#") item = QtWidgets.QGraphicsRectItem(-2 * 2, 2 * (7 * i + 4), 2.5, 0, seq_group) item.setPen(pen) item.setToolTip("Fa#") item = QtWidgets.QGraphicsRectItem(-2 * 2, 2 * (7 * i + 5), 2.5, 0, seq_group) item.setPen(pen) item.setToolTip("Sol#") item = QtWidgets.QGraphicsRectItem(-2 * 2, 2 * (7 * i + 6), 2.5, 0, seq_group) item.setPen(pen) item.setToolTip("La#") #Fin piano pen = QPen(QtGui.QColor("black"), 1 / 100) pen.setCapStyle(QtCore.Qt.SquareCap) path = QtGui.QPainterPath() path.moveTo(0, 0) path.lineTo(0, 49 * 2) item = QtWidgets.QGraphicsPathItem(path, seq_group) item.setPen(pen) #NoteLines pen = QPen(QtGui.QColor("black"), 1 / 100) pen.setCapStyle(QtCore.Qt.SquareCap) path = QtGui.QPainterPath() for i in range(49): path.moveTo(-4, 2 * i) path.lineTo(0, 2 * i) for i in range(7): path.moveTo(-4, 14 * i) path.lineTo(500, 14 * i) path.moveTo(0, 14 * i + 1.5) path.lineTo(500, 14 * i + 1.5) path.moveTo(0, 14 * i + 2.5) path.lineTo(500, 14 * i + 2.5) path.moveTo(0, 14 * i + 3.5) path.lineTo(500, 14 * i + 3.5) path.moveTo(0, 14 * i + 4.5) path.lineTo(500, 14 * i + 4.5) path.moveTo(-4, 14 * i + 6) path.lineTo(500, 14 * i + 6) path.moveTo(0, 14 * i + 7.5) path.lineTo(500, 14 * i + 7.5) path.moveTo(0, 14 * i + 8.5) path.lineTo(500, 14 * i + 8.5) path.moveTo(0, 14 * i + 9.5) path.lineTo(500, 14 * i + 9.5) path.moveTo(0, 14 * i + 10.5) path.lineTo(500, 14 * i + 10.5) path.moveTo(0, 14 * i + 11.5) path.lineTo(500, 14 * i + 11.5) path.moveTo(0, 14 * i + 12.5) path.lineTo(500, 14 * i + 12.5) item = QtWidgets.QGraphicsPathItem(path, seq_group) item.setPen(pen)
def __init__(self): # Создаём графический пользовательский интерфейс программы при помощи PyQt app = QtWidgets.QApplication(sys.argv) self.main_window = QtWidgets.QMainWindow() self.ui = UiMainWindow() self.ui.setupUi(self.main_window) self.main_window.show() # Инициализируем в конструкторе 3 будущих дерева элементов интерфейсов self.initial_tree = None self.optimized_tree = None self.best_tree = None # Создаём 2 графических сцены - для эталонного вида интерфейса и для модифицированного алгоритмами self.initial_scene = QtWidgets.QGraphicsScene() self.optimized_scene = QtWidgets.QGraphicsScene() # Создаём графическме группы для раздельного отображения схемы расположения элементов и тепловой карты self.initial_tree_group = QtWidgets.QGraphicsItemGroup() self.initial_heatmap_group = QtWidgets.QGraphicsItemGroup() self.optimized_tree_group = QtWidgets.QGraphicsItemGroup() self.optimized_heatmap_group = QtWidgets.QGraphicsItemGroup() # Инициализируем коэффициенты пропорциональности реальных размеров и размеров на graphicsView self.initial_scale_x = 1 self.initial_scale_y = 1 self.optimized_scale_x = 1 self.optimized_scale_y = 1 # Идентификатор узлов дерева self.identifier = 1 # Инициализируем списки точек для тепловых карт self.initial_points = [] self.optimized_points = [] # Контроль доступности кнопок управления self.loaded_interfaces = [False, False] # Параметры оптимизации self.count_iterations = 0 self.count_useless_iterations = 0 self.best_ff_value = 0 self.current_ff_value = 0 # PIL изображения тепловых карт self.destination_heatmap = None self.current_heatmap = None # Энергия системы зарядов эталонного интерфейса и коэффициент пропорциональности ФФ алгоритма системы зарядов self.initial_energy = 0 # Создаём экземпляр класса событий self.events = Events() self.events.generation_completed[str].connect(self.update_generation) # Поток для выполнения процесса эволюции по выбранному алгоритму self.evolution = None # Инициализируем обработчики нажатия кнопок self.ui.loadButton.clicked.connect(self.load_destination) self.ui.loadButton2.clicked.connect(self.load_test) self.ui.elementsCheckBox.stateChanged.connect(self.show_elements) self.ui.heatmapCheckBox.stateChanged.connect(self.show_heatmaps) self.ui.gaRadioButton.clicked.connect(self.update_ff_statistics) self.ui.beesRadioButton.clicked.connect(self.update_ff_statistics) self.ui.chargesRadioButton.clicked.connect(self.update_ff_statistics) self.ui.startButton.clicked.connect(self.start_evolution) # Запускаем бесконечный цикл обработки событий в PyQt sys.exit(app.exec_())
def __init__(self, event_dict, parent=None): super(EntryView, self).__init__(parent) self.setAttribute(qtc.Qt.WA_DeleteOnClose) self.setFlags(qtw.QGraphicsItem.ItemIsMovable | qtw.QGraphicsItem.ItemIsSelectable) self.setAcceptHoverEvents(True) self.setCursor(qtc.Qt.OpenHandCursor) self.setScale(1.4) self._event = event_dict self._id = self._event['event_id'] self.setObjectName('view{}'.format(self._id)) self.brush = qtg.QBrush( qtg.QColor('#c9cdd4')) # make dependent upon gender? kingdom? self.translucent_effect = qtw.QGraphicsOpacityEffect(self) self.translucent_effect.setOpacity(0.8) self.setGraphicsEffect(self.translucent_effect) self.translucent_effect.setEnabled(False) self.setSizePolicy(qtw.QSizePolicy.Preferred, qtw.QSizePolicy.Preferred) self.display_widgets = qtw.QGraphicsItemGroup(self) # Set layout layout = qtw.QGraphicsLinearLayout(qtc.Qt.Vertical) label_style = """ QLabel { background-color: #e3ddcc; border-radius: 5px; border-color: gray; padding: 4px; font: 24px; }""" # Create and add label widgets self.name_label = qtw.QGraphicsProxyWidget(self) self.name_label.setWidget(EntryViewLabel()) self.name_label.widget().setStyleSheet("""QLabel { background-color: rgba(255, 255, 255, 0); border-radius: 5px; border-color: gray; padding: 4px; font: 36px 'Didot'; }""") self.name_label.widget().setAlignment(qtc.Qt.AlignHCenter | qtc.Qt.AlignVCenter) self.name_label.setAcceptHoverEvents(False) layout.addItem(self.name_label) self.start_label = qtw.QGraphicsProxyWidget(self) self.start_label.setWidget(EntryViewLabel()) self.start_label.widget().setStyleSheet(label_style) self.start_label.setAcceptHoverEvents(False) layout.addItem(self.start_label) self.end_label = qtw.QGraphicsProxyWidget(self) self.end_label.setWidget(EntryViewLabel()) self.end_label.widget().setStyleSheet(label_style) self.end_label.setAcceptHoverEvents(False) layout.addItem(self.end_label) self.loc_label = qtw.QGraphicsProxyWidget(self) self.loc_label.setWidget(EntryViewLabel()) self.loc_label.widget().setStyleSheet(label_style) self.loc_label.setAcceptHoverEvents(False) layout.addItem(self.loc_label) self.updateView() self.cancel_btn = qtw.QGraphicsProxyWidget(self) self.cancel_btn.setWidget(qtw.QPushButton('Cancel', clicked=self.close)) self.cancel_btn.widget().setStyleSheet(""" QPushButton { border: 1px solid black; border-style: outset; border-radius: 2px; color: black; font: 24px; font-family: Baskerville; } QPushButton:pressed { background-color: rgba(255, 255, 255, 70); border-style: inset; }""") layout.addItem(self.cancel_btn) layout.setSpacing(16) self.setLayout(layout)
def __init__( self, scene, frame_length, init_pos, wheel_size): super(Articulated, self).__init__() # model place self.model = articulated_model.ArticulatedModel( frame_length=frame_length, wheel_rad=wheel_size["diameter"] / 2, max_angle=self.front_angle_max, angle_change=1, update_freq=30, bw_pos=init_pos["position"], heading=init_pos["heading"]) # 1. back wheels axis self.back_wheels_axis = QtWidgets.QGraphicsRectItem( - self.wheels_axis_breadth / 2, - self.wheels_dist / 2, self.wheels_axis_breadth, self.wheels_dist, self) self.back_wheels_axis.setPos(0, 0) # 2. back left wheel self.back_wheel_left = QtWidgets.QGraphicsRectItem( - wheel_size["diameter"] / 2, - wheel_size["breadth"] / 2, wheel_size["diameter"], wheel_size["breadth"], self) self.back_wheel_left.setPos( 0, - wheel_size["breadth"] / 2 - self.wheels_dist / 2) # 3. back right wheel self.back_wheel_right = QtWidgets.QGraphicsRectItem( - wheel_size["diameter"] / 2, - wheel_size["breadth"] / 2, wheel_size["diameter"], wheel_size["breadth"], self) self.back_wheel_right.setPos( 0, wheel_size["breadth"] / 2 + self.wheels_dist / 2) # 4. frame_back self.frame_back = QtWidgets.QGraphicsRectItem( - frame_length["back"] / 2, - self.body_breadth / 2, frame_length["back"], self.body_breadth, self) self.frame_back.setPos( frame_length["back"] / 2 + self.wheels_axis_breadth / 2, 0) # 5. point of articulation self.point_of_articulation = QtWidgets.QGraphicsEllipseItem( 0 - 2.5, 0 - 2.5, 5, 5, self) self.point_of_articulation.setPos( frame_length["back"] + self.wheels_axis_breadth / 2, 0) # 6. prepare front self.front = QtWidgets.QGraphicsItemGroup(self) # 7. frame_front self.frame_front = QtWidgets.QGraphicsRectItem( - frame_length["front"] / 2, - self.body_breadth / 2, frame_length["front"], self.body_breadth, self.front) self.frame_front.setPos( frame_length["front"] / 2, 0) # 8. front wheels axis self.front_wheels_axis = QtWidgets.QGraphicsRectItem( - self.wheels_axis_breadth / 2, - self.wheels_dist / 2, self.wheels_axis_breadth, self.wheels_dist, self.front) self.front_wheels_axis.setPos( frame_length["front"] + self.wheels_axis_breadth / 2, 0) # 9. front right wheel self.front_wheel_right = QtWidgets.QGraphicsRectItem( - wheel_size["diameter"] / 2, - wheel_size["breadth"] / 2, wheel_size["diameter"], wheel_size["breadth"], self.front) self.front_wheel_right.setPos( frame_length["front"] + self.wheels_axis_breadth / 2, wheel_size["breadth"] / 2 + self.wheels_dist / 2) # 10. front left wheel self.front_wheel_right = QtWidgets.QGraphicsRectItem( - wheel_size["diameter"] / 2, - wheel_size["breadth"] / 2, wheel_size["diameter"], wheel_size["breadth"], self.front) self.front_wheel_right.setPos( frame_length["front"] + self.wheels_axis_breadth / 2, - wheel_size["breadth"] / 2 - self.wheels_dist / 2) # 11. setup all front position self.front.setPos( frame_length["back"], 0) # 12. setup front angle initial self.front_angle = self.front_angle_init self.front.setRotation(self.front_angle) # 13. initial heading and pos self.setPos(init_pos["position"]) self.setRotation(init_pos["heading"]) # 14. rotation line self.rotation_line = None