def checkCursor(self): # ignore if the link context menu is visible for menu in self.findChildren( QtWidgets.QMenu, options=QtCore.Qt.FindDirectChildrenOnly): if menu.isVisible(): return # an arbitrary check for mouse position; since we have to be able to move # inside the tooltip margins (standard QToolTip hides itself on hover), # let's add some margins just for safety region = QtGui.QRegion(self.geometry().adjusted(-10, -10, 10, 10)) if self.refWidget: rect = self.refWidget.rect() rect.moveTopLeft(self.refWidget.mapToGlobal(QtCore.QPoint())) region |= QtGui.QRegion(rect) else: # add a circular region for the mouse cursor possible range rect = QtCore.QRect(0, 0, 16, 16) rect.moveCenter(self.refPos) region |= QtGui.QRegion(rect, QtGui.QRegion.Ellipse) if QtGui.QCursor.pos() not in region: self.hide()
def on_view_horizontalHeader_sectionClicked(self, logicalIndex): self.logicalIndex = logicalIndex self.menuValues = QtWidgets.QMenu(self) self.signalMapper = QtCore.QSignalMapper(self) self.comboBox.blockSignals(True) self.comboBox.setCurrentIndex(logicalIndex) self.comboBox.blockSignals(True) valuesUnique = self.model._df.iloc[:, logicalIndex].unique() #print(valuesUnique) if logicalIndex == 0: valuesUnique = ['Sort: 0-9', 'Sort: 9-0'] elif logicalIndex == 2: valuesUnique = [ 'Exclude N/A', 'Only N/A', 'Sort: A-Z', 'Sort: Z-A' ] elif logicalIndex == 3: valuesUnique = ['Sort: A-Z', 'Sort: Z-A'] elif logicalIndex == 4 or logicalIndex == 5: valuesUnique = [ 'Exclude N/A', 'Only N/A', 'Sort: A-Z', 'Sort: Z-A' ] actionAll = QtWidgets.QAction("All", self) actionAll.triggered.connect(self.on_actionAll_triggered) self.menuValues.addAction(actionAll) self.menuValues.addSeparator() for actionNumber, actionName in enumerate( sorted(list(set(valuesUnique)))): action = QtWidgets.QAction(actionName, self) self.signalMapper.setMapping(action, actionNumber) action.triggered.connect(self.signalMapper.map) self.menuValues.addAction(action) self.signalMapper.mapped.connect(self.on_signalMapper_mapped) headerPos = self.ncbi_table.mapToGlobal(self.horizontalHeader.pos()) posY = headerPos.y() + self.horizontalHeader.height() posX = headerPos.x() + self.horizontalHeader.sectionViewportPosition( logicalIndex) self.menuValues.exec_(QtCore.QPoint(posX, posY))
class Target: """ This is the Target class. It is a data structure for storing a point (Starting location or target point). Inherits: None Returns: None """ location = QtCore.QPoint(0, 0) def __init__(self, x, y): """ This is the constructor for the Target class Args: x (float): the x coordinate value y (float): the y coordinate value Returns: None """ self.location = QtCore.QPoint(int(x), int(y)) def getLocation(self): """ This returns the target location as x,y. Args: None Returns: (float): the x location coordinate value (float): the y location coordinate value """ return self.location.x(), self.location.y()
def mousePressEvent(self, event): if event.button() == QtCore.Qt.LeftButton: position = QtCore.QPoint(event.pos()) if self.selection.isVisible(): # visible selection if (self.upper_left - position).manhattanLength() < 20: # close to upper left corner, drag it self.mode = "drag_upper_left" elif (self.lower_right - position).manhattanLength() < 20: # close to lower right corner, drag it self.mode = "drag_lower_right" else: # clicked somewhere else, hide selection self.pixMapToShare = self.cropQPixmap self.pixMapToShare.save("samples/sample2.png","PNG") self.selection.hide() else: # no visible selection, start new selection self.upper_left = position self.lower_right = position self.mode = "drag_lower_right" self.selection.show()
def paintEvent(self, event): painter = QtWidgets.QStylePainter(self) option = QtWidgets.QStyleOptionTab() painter.begin(self) for index in range(self.count()): self.initStyleOption(option, index) painter.drawControl(QtWidgets.QStyle.CE_TabBarTabShape, option) painter.save() s = option.rect.size() s.transpose() r = QtCore.QRect(QtCore.QPoint(), s) r.moveCenter(option.rect.center()) option.rect = r c = self.tabRect(index).center() painter.translate(c) painter.rotate(90) painter.translate(-c) painter.drawControl(QtWidgets.QStyle.CE_TabBarTabLabel, option) painter.restore() painter.end()
def btn_func_load(self, value): """ Function to load an image from the current scene dir. """ if value == -1: value = random.randrange(1000) self.load_slider.setValue(value) read_indx = int(int(value) * (len(self.img_name_list[:-1])) / 1000) # Read the RGB, Depth image and Camera pose at the index read_pair = (self.img_name_list[read_indx]).split() dep_im_path = os.path.join(self.scenes[self._count].path, read_pair[1]) rgb_im_path = os.path.join(self.scenes[self._count].path, read_pair[3]) self.current_rgb_image = cv2.resize( cv2.cvtColor(cv2.imread(rgb_im_path), cv2.COLOR_BGR2RGB), (self.width, self.height)) self.current_dep_image = cv2.resize( cv2.imread(dep_im_path, cv2.IMREAD_ANYDEPTH), (self.width, self.height)) self.current_cam_pos = self.cam_pose_list[read_indx] # Get projection of keypoints on current image matched = self.process.get_projection(self.scenes[self._count].labels, self.current_cam_pos) # Update canvas pixmap = QtGui.QPixmap(rgb_im_path) self.canvas.loadPixmap(pixmap) self.canvas.locked_points = [ QtCore.QPoint(point[0], point[1]) for point in matched ] self.canvas.update() # Configure state of widgets self.skip_btn.setEnabled(True) self.display_btn.setEnabled(True) # Update status bar self.statusBar().showMessage( "Loaded image\nfrom scene {}".format( self.scenes[self._count].name), 5000)
def test_linux_autostart(qapp, qtbot): main = qapp.main_window main.tabWidget.setCurrentIndex(4) tab = main.miscTab for x in range(0, tab.checkboxLayout.count()): checkbox = tab.checkboxLayout.itemAt(x).widget() checkbox.__class__ = QCheckBox if checkbox.text().startswith("Automatically"): # Have to use pos to click checkbox correctly # https://stackoverflow.com/questions/19418125/pysides-qtest-not-checking-box/24070484#24070484 qtbot.mouseClick(checkbox, QtCore.Qt.LeftButton, pos=QtCore.QPoint(2, checkbox.height() / 2)) break autostart_path = Path(os.environ.get( "XDG_CONFIG_HOME", os.path.expanduser("~") + '/.config') + "/autostart") / "vorta.desktop" qtbot.waitUntil(lambda: autostart_path.exists(), timeout=5000) with open(autostart_path) as desktop_file: desktop_file_text = desktop_file.read() assert(desktop_file_text.startswith("[Desktop Entry]"))
def draw(self, qp): begin = QPoint(self.x, self.y) * self.scale end = QtCore.QPoint(self.x + self.width - 2, self.y + self.height - 2) * self.scale gradient = QtGui.QRadialGradient(QPointF(begin), 3000) gradient.setColorAt(0.0, QtCore.Qt.white) gradient.setColorAt(0.2, QtCore.Qt.darkGray) gradient.setColorAt(0.8, QtCore.Qt.darkGray) gradient.setColorAt(0.99, QtCore.Qt.gray) solid = QBrush(self.color) qp.setBrush(solid) qp.drawRect(QRect(begin, end)) myPixmap = QtGui.QPixmap('grid2.jpg') # myScaledPixmap = myPixmap.scaled(QSize(2,2), QtCore.Qt.KeepAspectRatio) # qp.drawPixmap(QRect(QPoint(0,0), QPoint(1920,1138)), myPixmap) qp.drawPixmap(QRect(begin, end), myPixmap) for n in self.nodes: self.nodes[n].draw(qp) for l in self.links: l.draw(qp)
def paintEvent(self, event): """Painting the view, if there is a root item""" if self.itemAt(0, 0) is None: return painter = QPainter(self.viewport()) self.makeImage(painter) # drawing the dragged item if (self.dragMod and self.dragSource == self.source and self.currentItem() is not None): pos = self.lastp - QtCore.QPoint(self.minr/4, self.minr/4) self.paintItem(self.currentItem(), pos, painter, self.xml) if self.timeline is None: # paintItem saves the drawn node. But the dragged Node is not # fixed thats why I remove it again. del self.nodeCopy[-1] painter.end()
def mousePressEvent(self, event): x, y = event.pos().x(), event.pos().y() topleft = getTopLeft(self.pos1, self.pos2) bottomright = getBottomRight(self.pos1, self.pos2) if self.drawer.ableToDraw: if event.button() == QtCore.Qt.RightButton: position = QtCore.QPoint(0, 0) pressEvent = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, position, QtCore.Qt.RightButton, QtCore.Qt.RightButton, QtCore.Qt.NoModifier) releaseEvent = QtGui.QMouseEvent( QtCore.QEvent.MouseButtonRelease, position, QtCore.Qt.RightButton, QtCore.Qt.RightButton, QtCore.Qt.NoModifier) self.colorWidget.mousePressEvent(pressEvent) self.colorWidget.mouseReleaseEvent(releaseEvent) else: self.drawer.startDrawing(event.pos()) self.effSetCursor(Cursors.draw) else: if not self.firstChosen: self.mouseToolTip.hide() self.selecting = True self.firstChosen = True self.updateDraggingStatus(x, y) if not self.isDragging(): if (topleft[0] < x < bottomright[0]) and ( topleft[1] < y < bottomright[1]): # mouse inside rect, drag it self.moving = x, y # initial position else: # new rect self.pos1[0], self.pos1[1] = x, y self.AOIRemoved.emit() return super(CaptureLabel, self).mousePressEvent(event)
def updateLabelPos(self): center = self.geometry().center() origins = [qtcore.QPoint(center) for label in self.labels] for origin, col in zip(origins, range(len(origins))): for label in self.labels[0:col]: # put label underneath each other origin.setY(origin.y() + label.height()) # move labels up to have the middle one in the center origin.setY(origin.y() - sum([label.height() for label in self.labels]) / 2) # move labels left to have them in the center origin.setX(origin.x() - self.labels[col].width() / 2 + 2) if self.labelAlignment == qt.AlignLeft: maxWidth = max([label.width() for label in self.labels]) for label, origin in zip(self.labels, origins): origin.setX(origin.x() - (maxWidth - label.width()) / 2) elif self.labelAlignment == qt.AlignRight: maxWidth = max([label.width() for label in self.labels]) for label, origin in zip(self.labels, origins): origin.setX(origin.x() + (maxWidth - label.width()) / 2) for label, origin in zip(self.labels, origins): label.move(origin)
def test_move_point(self, mockbox): self.window.mpl.navbar._actions['insert_wp'].trigger() QtWidgets.QApplication.processEvents() assert len(self.window.waypoints_model.waypoints) == 3 QtWidgets.QApplication.processEvents() QtTest.QTest.mouseClick(self.window.mpl.canvas, QtCore.Qt.LeftButton) QtWidgets.QApplication.processEvents() assert len(self.window.waypoints_model.waypoints) == 4 self.window.mpl.navbar._actions['move_wp'].trigger() QtWidgets.QApplication.processEvents() QtTest.QTest.mousePress(self.window.mpl.canvas, QtCore.Qt.LeftButton) QtWidgets.QApplication.processEvents() point = QtCore.QPoint((self.window.width() // 3), self.window.height() // 2) QtTest.QTest.mouseMove(self.window.mpl.canvas, pos=point) QtWidgets.QApplication.processEvents() QtTest.QTest.mouseRelease(self.window.mpl.canvas, QtCore.Qt.LeftButton, pos=point) QtWidgets.QApplication.processEvents() assert len(self.window.waypoints_model.waypoints) == 4 assert mockbox.critical.call_count == 0
def __init__(self): super().__init__() # locale.setlocale(locale.LC_TIME, 'fr_FR.UTF-8') timer = QtCore.QTimer(self) timer.timeout.connect(self.update) timer.start(1000) self.color = QtGui.QColor(113, 249, 76) self.needles_color = QtGui.QColor(84, 189, 55) self.hour_hand = QtGui.QPolygon( [QtCore.QPoint(0, 0), QtCore.QPoint(0, -50)]) self.minute_hand = QtGui.QPolygon( [QtCore.QPoint(0, 0), QtCore.QPoint(0, -70)]) self.second_hand = QtGui.QPolygon( [QtCore.QPoint(0, 0), QtCore.QPoint(0, -80)])
def _doShowPreview(self, path, row, pixmap): if pixmap and row == self.currentRow(): lab = self._tempIconWindow = QtWidgets.QLabel() lab.mouseDoubleClickEvent = lambda _evt, path = path: \ self._open(path) lab.setPixmap(pixmap) lab.setWindowFlags(QtCore.Qt.FramelessWindowHint | QtCore.Qt.SubWindow ) lab.setAttribute(QtCore.Qt.WA_ShowWithoutActivating) p0 = self.mapToGlobal(self.parent().pos()) p1 = QtCore.QPoint(0, # -pixmap.size().width(), self.rowViewportPosition(self._Lrow)) # del self._Lrow self._prefWinFn = lambda p, p1 = p1: lab.move( p + p1 + self.mapTo(self.gui, self.parent().pos())) self.gui.sigMoved.connect(self._prefWinFn) self.gui.tabs.currentChanged.connect(self._closePreview) lab.move(p0 + p1) # if the context menu is vsibile before (right clicked on a row # then showing preview will hide it again # we dont want this - we make menu visibe afterwards try: menu_visible = self._menu.isVisible() except AttributeError: menu_visible = False lab.show() if menu_visible: self._menu.setVisible(True)
def __init__(self, parent, sharedGLWidget, verticalScaleTransform, horizontalScaleTransform): super(GlCanvasWidget, self).__init__(parent, shareWidget=sharedGLWidget) self.lastPos = QtCore.QPoint() self.xMajorTick = np.array([]) self.xMinorTick = np.array([]) self.yMajorTick = np.array([]) self.yMinorTick = np.array([]) self.ruler = False self.mousex = 0 self.mousey = 0 self.showFreqLabel = False self.xmax = 0 self.fmax = 0. # use a cross cursor to easily select a point on the graph self.setCursor(Qt.Qt.CrossCursor) # instruct OpenGL not to paint a background for the widget # when QPainter.begin() is called. self.setAutoFillBackground(False) # set proper size policy for this widget self.setSizePolicy(QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding)) self.attachedItems = [] self.gridList = None self.horizontalScaleTransform = horizontalScaleTransform self.verticalScaleTransform = verticalScaleTransform self.trackerFormatter = lambda x, y: "x=%d, y=%d" %(x, y) self.anyOpaqueItem = False
def drawOnImage(self, event): zoom_corrected_pos = event.pos() / self.scale if self.drawing and (event.buttons() == QtCore.Qt.LeftButton or event.buttons() == QtCore.Qt.RightButton): # now drawing or erasing over the image painter = QtGui.QPainter(self.imageDraw) if event.buttons() == QtCore.Qt.LeftButton: painter.setPen(QtGui.QPen(self.drawColor, self.brushSize, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin)) else: painter.setPen(QtGui.QPen(self.eraseColor, self.brushSize, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin)) if self.lastPoint != zoom_corrected_pos: painter.drawLine(self.lastPoint, zoom_corrected_pos) else: # if zero length line then draw point instead painter.drawPoint(zoom_corrected_pos) painter.end() # Drawing the cursor TODO add boolean to ask if drawing cursor should be shown painter = QtGui.QPainter(self.cursor) # We erase previous pointer r = QtCore.QRect(QtCore.QPoint(), self._clear_size * QtCore.QSize() * self.brushSize) painter.save() r.moveCenter(self.lastPoint) painter.setCompositionMode(QtGui.QPainter.CompositionMode_Clear) painter.eraseRect(r) painter.restore() # draw the new one painter.setPen(QtGui.QPen(self.cursorColor, 2, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin)) painter.drawEllipse(zoom_corrected_pos, self.brushSize / 2., self.brushSize / 2.) painter.end() region = self.scrollArea.widget().visibleRegion() self.update(region) # required to erase mouse pointer self.lastPoint = zoom_corrected_pos
def annotation_list_right_clicked(self, QPos): self.listMenu = QtWidgets.QMenu() parent_position = self.w_dblist.mapToGlobal(QtCore.QPoint(0, 0)) item = self.w_dblist.itemAt(QPos) data = item.data(QtCore.Qt.UserRole) db = data.get('_db_interface', None) if db is None: logger.debug('No database for selected item') return menu_details = self.listMenu.addAction("Details") menu_details.triggered.connect(lambda: self.right_menu_details(item)) if db.annotatable: menu_details = self.listMenu.addAction("Update annotation") menu_details.triggered.connect( lambda: self.right_menu_update(item)) menu_delete = self.listMenu.addAction("Delete annotation") menu_delete.triggered.connect(lambda: self.right_menu_delete(item)) menu_remove = self.listMenu.addAction( "Remove seq. from annotation") menu_remove.triggered.connect( lambda: self.right_menu_remove_feature(item)) self.listMenu.move(parent_position + QPos) self.listMenu.show()
def draw_line_label(self, painter, zoomed, label): """ add the label to a single line segment Args: painter (QPainter) the painter to be used for the drawing, with pen set zoomed (ImageLineSegment) the line that needs labelling, with current zoom applied label (string) a label for the line Returns: None """ # find the bounding box for the text bounding_box = qc.QRect(1, 1, 1, 1) bounding_box = painter.boundingRect(bounding_box, qc.Qt.AlignCenter, label) point = zoomed.start location = qc.QPoint(point.x, point.y) bounding_box = qc.QRect(location, bounding_box.size()) painter.drawText(bounding_box, qc.Qt.AlignHorizontal_Mask | qc.Qt.AlignVertical_Mask, label)
def test_insert_point(self, mockbox): """ Test inserting a point inside and outside the canvas """ self.window.mpl.navbar._actions['insert_wp'].trigger() QtWidgets.QApplication.processEvents() assert len(self.window.waypoints_model.waypoints) == 3 point = self.window.mpl.canvas.rect().center() QtTest.QTest.mouseClick(self.window.mpl.canvas, QtCore.Qt.LeftButton, pos=point) QtWidgets.QApplication.processEvents() assert len(self.window.waypoints_model.waypoints) == 4 QtTest.QTest.mouseClick(self.window.mpl.canvas, QtCore.Qt.LeftButton, pos=QtCore.QPoint(1, 1)) QtWidgets.QApplication.processEvents() assert len(self.window.waypoints_model.waypoints) == 4 QtTest.QTest.mouseClick(self.window.mpl.canvas, QtCore.Qt.LeftButton) # click again on same position QtWidgets.QApplication.processEvents() assert len(self.window.waypoints_model.waypoints) == 5 assert mockbox.critical.call_count == 0
def pixelSelect(self, event): position = QtCore.QPoint( event.pos().x(), event.pos().y()) #Obtener un punto con las coordenadas clickeadas. #Brushes para los rectangulos negro = QtGui.QColor(0, 0, 0, 255) blanco = QtGui.QColor(255, 255, 255, 255) brushnegro = QtGui.QBrush(negro) brushblanco = QtGui.QBrush(blanco) for i in range(len(self.listaRec)): for j in range(len(self.listaRec[i])): #Rectangulo que clickees se volvera negro y el valor del laberinto sera 1 (bloqueo) if self.listaRec[i][j].contains( position) and self.array[i][j] == 0: self.listaRec[i][j].setBrush(brushnegro) self.array[i][j] = 1 #Lo mismo pero diferente elif self.listaRec[i][j].contains( position) and self.array[i][j] == 1: self.listaRec[i][j].setBrush(brushblanco) self.array[i][j] = 0
def update_frame_keypoint(self, cid, kp, pos, is_scene_pos=True): ident = '%d_%s' % (cid, kp['name']) if ident not in self.frame_keypoints: if self.verbose: print('Creating frame keypoint', ident) # create because not existant yet self.frame_keypoints[ident] = FrameKeypointItem( self.photo, ident, self.kp_radius, QtGui.QColor.fromRgb(*kp['color']), self.kp_width, kp['name'], cid) self.frame_keypoints[ident].kpMove.connect(self.handle_kp_moved) self.frame_keypoints[ident].kpReset.connect(self.handle_kp_reset) if not is_scene_pos: # usually we get a scenepos except for when it was created by the app, then we have to do conversion # map from original image to stitch u, v = self.stitch_img.map_orig2stitch(pos[0], pos[1], cid) pos = QtCore.QPoint(u, v) # move to location self.frame_keypoints[ident].setPos(pos) self.frame_keypoints[ident].setVisible(True) self.frame_keypoints[ident].is_valid = True
def resizeEvent(self, event): """ Handle the resize event of the window. """ if event.size().isValid() and event.oldSize().isValid(): w = event.size().width() h = event.size().height() dw = w - event.oldSize().width() dh = h - event.oldSize().height() print("Resized window to ({:d}, {:d})".format(w, h)) sz = self.date_controls.size() self.date_controls.resize(sz.width() + dw, sz.height()) sz = self.splitter_area.size() self.splitter_area.resize(sz.width() + dw, sz.height() + dh) self.splitter.resize(self.splitter_area.size()) self.spec_fig.tight_layout() ps = self.close_button.pos() self.close_button.move(QtCore.QPoint(ps.x() + dw, ps.y() + dh)) else: QtWidgets.QMainWindow.resizeEvent(self, event)
def xas_project_context_menu(self, QPos): menu = QMenu() rename_action = menu.addAction("&Rename") merge_action = menu.addAction("&Merge") remove_action = menu.addAction("&Remove") save_datasets_as_text_action = menu.addAction("&Save datasets as text") combine_and_save_datasets_as_text_action = menu.addAction("&Combine and save datasets as text") save_dataset_to_database_action = menu.addAction("&Save to processed database") parentPosition = self.list_project.mapToGlobal(QtCore.QPoint(0, 0)) menu.move(parentPosition + QPos) action = menu.exec_() if action == rename_action: self.rename_dataset() elif action == merge_action: self.merge_datasets() elif action == remove_action: self.remove_from_xas_project() elif action == combine_and_save_datasets_as_text_action: self.combine_and_save_datasets_as_text() elif action == save_datasets_as_text_action: self.save_datasets_as_text() elif action == save_dataset_to_database_action: self.save_datasets_to_database()
def slot_add_genre_clicked(self): log.debug('slot_add_genre_clicked') if self.pop_form is None: lw = QtWidgets.QListWidget() for each in self.data.mold_genre: item = QtWidgets.QListWidgetItem(lw) # 创建QListWidgetItem对象 item.setSizeHint(QtCore.QSize(50, 30)) # 设置QListWidgetItem大小 item.setText(each[1]) item.setIcon(QtGui.QIcon(f'{self.data.dir_icons}{each[0]}')) lw.addItem(item) # 添加item lw.setCurrentRow(0) lw.resize(200, 30 * (len(self.data.mold_genre) + 1)) lw.itemClicked.connect(self.slot_genre_item_clicked) self.pop_form = PopForm(self.folder, lw) ps = QtCore.QPoint(self.wg_card.width() - self.pop_form.width(), self.wg_card.y() + self.wg_card.height() - 18) self.pop_form.move(ps) log.debug(ps) else: self.pop_form.show() log.debug('no')
def __init__(self, vStream, parent, hideRectangle=True): """ :param hideRectangle: If True, then when something is selected, the rubber band won't go away. :param parent: The GUI Parent of this widget """ super(CameraSelector, self).__init__(vStream, parent) # Set up the rubberBand specific variables (for rectangle drawing) self.rectangle = QtWidgets.QRubberBand(QtWidgets.QRubberBand.Rectangle, self) self.hideRectangle = hideRectangle self.origin = QtCore.QPoint() self.vStream = vStream # When the user has something selected, this is a frame. Otherwise, it is None self.selectedImage = None self.selectedRect = None # The coordinates of the object inside of self.selectedImage. (x1,y1,x2,y2) format. # Make sure that the QRect is aligned with the picture by adding a stretch and setting the contents margins! self.layout().addStretch( 1 ) # Push the layout to the top, so the mouse commands align correctly
def paintEvent(self, e): self.setPalette(self.pal) painter = QtGui.QPainter(self) painter.drawText( QtCore.QRect(QtCore.QPoint(10, 0), QtCore.QSize(150, 20)), QtCore.Qt.AlignLeft, self.nome + " " + self.tipo) if self.rettangoli: spostat = self.offsetWindow + self.posIniziale - self.posFinale if spostat < 0: spostat = 0 self.offsetWindow = 0 self.posIniziale = self.posFinale painter.setWindow(spostat, 0, self.width(), self.height()) painter.setPen(QtGui.QPen(QtCore.Qt.black, 1, QtCore.Qt.SolidLine)) for elemento in self.rettangoli: painter.setBrush(elemento[1]) painter.drawRect(elemento[0]) for elemento in self.labels: painter.drawText(elemento[0], QtCore.Qt.AlignCenter, elemento[1]) for linea in self.linee: painter.drawLine(linea)
class LogView(LogViewCommon): options = [ config.Option("persist", "logview_position", QtCore.QPoint()), config.Option("persist", "logview_size", QtCore.QSize(560, 400)), ] def __init__(self, parent=None): title = _("Log") logger = log.main_logger LogViewCommon.__init__(self, title, logger, parent=parent) self.restoreWindowState("logview_position", "logview_size") cb = QtWidgets.QCheckBox(_('Debug mode'), self) cb.setChecked(QtCore.QObject.tagger._debug) cb.stateChanged.connect(self.toggleDebug) self.vbox.addWidget(cb) def toggleDebug(self, state): QtCore.QObject.tagger.debug(state == QtCore.Qt.Checked) def closeEvent(self, event): self.saveWindowState("logview_position", "logview_size") event.accept()
def __init__(self): super().__init__() chart = qtch.QChart(title=self.chart_title) self.setChart(chart) self.series = qtch.QSplineSeries(name='Percentage') chart.addSeries(self.series) self.data = deque([0] * self.num_data_points, maxlen=self.num_data_points) self.series.append([qtc.QPoint(x, y) for x, y in enumerate(self.data)]) x_axis = qtch.QValueAxis() x_axis.setRange(0, self.num_data_points) x_axis.setLabelsVisible(False) y_axis = qtch.QValueAxis() y_axis.setRange(0, 100) chart.setAxisX(x_axis, self.series) chart.setAxisY(y_axis, self.series) self.setRenderHint(qtg.QPainter.Antialiasing) self.timer = qtc.QTimer(interval=200, timeout=self.refresh_stats) self.timer.start()
def _coerce_point(self, point): # Get the coordinates x, y = point.x(), point.y() x_max, y_max = self.pixmapToDisplay.width( ), self.pixmapToDisplay.height() # Coerce low limit if x < 0: x = 0 if y < 0: y = 0 # Coerce the highest limit if x >= x_max: x = x_max - 1 if y >= y_max: y = y_max - 1 # Convert back into a point point = qtc.QPoint(x, y) return point
def doLayout(self, rect, testOnly): x = rect.x() y = rect.y() lineHeight = 0 for item in self.itemList: wid = item.widget() spaceX = self.spacing() + wid.style().layoutSpacing(QtGui.QSizePolicy.PushButton, QtGui.QSizePolicy.PushButton, QtCore.Qt.Horizontal) spaceY = self.spacing() + wid.style().layoutSpacing(QtGui.QSizePolicy.PushButton, QtGui.QSizePolicy.PushButton, QtCore.Qt.Vertical) nextX = x + item.sizeHint().width() + spaceX if nextX - spaceX > rect.right() and lineHeight > 0: x = rect.x() y = y + lineHeight + spaceY nextX = x + item.sizeHint().width() + spaceX lineHeight = 0 if not testOnly: item.setGeometry(QtCore.QRect(QtCore.QPoint(x, y), item.sizeHint())) x = nextX lineHeight = max(lineHeight, item.sizeHint().height()) return y + lineHeight - rect.y()