def _update_overlay_geometry(self, widget, centered, padding): """Reposition/resize the given overlay.""" if not widget.isVisible(): return size_hint = widget.sizeHint() if widget.sizePolicy().horizontalPolicy() == QSizePolicy.Expanding: width = self.width() - 2 * padding left = padding else: width = size_hint.width() left = (self.width() - size_hint.width()) / 2 if centered else 0 height_padding = 20 status_position = config.get('ui', 'status-position') if status_position == 'bottom': top = self.height() - self.status.height() - size_hint.height() top = qtutils.check_overflow(top, 'int', fatal=False) topleft = QPoint(left, max(height_padding, top)) bottomright = QPoint(left + width, self.status.geometry().top()) elif status_position == 'top': topleft = QPoint(left, self.status.geometry().bottom()) bottom = self.status.height() + size_hint.height() bottom = qtutils.check_overflow(bottom, 'int', fatal=False) bottomright = QPoint(left + width, min(self.height() - height_padding, bottom)) else: raise ValueError("Invalid position {}!".format(status_position)) rect = QRect(topleft, bottomright) log.misc.debug('new geometry for {!r}: {}'.format(widget, rect)) if rect.isValid(): widget.setGeometry(rect)
def paintEvent(self, event): rect = QRect(10, 20, 80, 60) path = QPainterPath() path.moveTo(20, 80) path.lineTo(20, 30) path.cubicTo(80, 0, 50, 50, 80, 80) startAngle = 30 * 16 arcLength = 120 * 16 painter = QPainter(self) painter.setPen(self.pen) painter.setBrush(self.brush) if self.antialiased: painter.setRenderHint(QPainter.Antialiasing) for x in range(0, self.width(), 100): for y in range(0, self.height(), 100): painter.save() painter.translate(x, y) if self.transformed: painter.translate(50, 50) painter.rotate(60.0) painter.scale(0.6, 0.9) painter.translate(-50, -50) if self.shape == RenderArea.Line: painter.drawLine(rect.bottomLeft(), rect.topRight()) elif self.shape == RenderArea.Points: painter.drawPoints(RenderArea.points) elif self.shape == RenderArea.Polyline: painter.drawPolyline(RenderArea.points) elif self.shape == RenderArea.Polygon: painter.drawPolygon(RenderArea.points) elif self.shape == RenderArea.Rect: painter.drawRect(rect) elif self.shape == RenderArea.RoundedRect: painter.drawRoundedRect(rect, 25, 25, Qt.RelativeSize) elif self.shape == RenderArea.Ellipse: painter.drawEllipse(rect) elif self.shape == RenderArea.Arc: painter.drawArc(rect, startAngle, arcLength) elif self.shape == RenderArea.Chord: painter.drawChord(rect, startAngle, arcLength) elif self.shape == RenderArea.Pie: painter.drawPie(rect, startAngle, arcLength) elif self.shape == RenderArea.Path: painter.drawPath(path) elif self.shape == RenderArea.Text: painter.drawText(rect, Qt.AlignCenter, "PyQt by\nRiverbank Computing") elif self.shape == RenderArea.Pixmap: painter.drawPixmap(10, 10, self.pixmap) painter.restore() painter.setPen(self.palette().dark().color()) painter.setBrush(Qt.NoBrush) painter.drawRect(QRect(0, 0, self.width() - 1, self.height() - 1))
def _redrawColorLabel(self, labelIndex, lc, uc, lValue, uValue) : if labelIndex >= len(self.__colorLabels) : return label = self.__colorLabels[labelIndex] pixmap = QPixmap(101, 26) painter = QPainter(pixmap) lowerColorRect = QRect(0, 0, 50, 25) upperColorRect = QRect(50, 0, 50, 25) font = QFont('Times', 11) painter.setFont(font) painter.setPen(Qt.black); painter.setBrush(lc); painter.drawRect(lowerColorRect); painter.setPen(self.invert(lc)); painter.drawText(lowerColorRect.translated(8, 2), 0, str(lValue)); painter.setPen(Qt.black); painter.setBrush(uc); painter.drawRect(upperColorRect); painter.setPen(self.invert(uc)); painter.drawText(upperColorRect.translated(8, 2), 0, str(uValue)); del painter label.setPixmap(pixmap);
def calculate_relative_position(parent_rect: QtCore.QRect, own_size: QtCore.QSize, constraint: RelativeLayoutConstraint): """ Calculates the position of the element, given its size, the position and size of the parent and a relative layout constraint. The position is the position of the parent plus the weighted size of the parent, the weighted size of the element and an offset. The weights and the offset are given by the constraint for each direction. :param parent_rect: parent coordinates and size as rectangle :param own_size: size of the element (width and height) :param constraint: relative layout constraint to apply :return: tuple of recommended x and y positions of the element """ """ Returns the left, upper corner of an object if the parent rectangle (QRect) is given and our own size (QSize) and a relative layout constraint (see RelativeLayoutConstraint). """ x = (parent_rect.x() + constraint.x[0] * parent_rect.width() + constraint.x[1] * own_size.width() + constraint.x[2]) y = (parent_rect.y() + constraint.y[0] * parent_rect.height() + constraint.y[1] * own_size.height() + constraint.y[2]) return x, y
def request(self, qrect, along_through=None): assert isinstance(qrect, QRect) # Widen request with a 1-pixel halo, to make sure edges on the tile borders are shown. qrect = QRect(qrect.x(), qrect.y(), qrect.width() + 1, qrect.height() + 1) s = rect2slicing(qrect) arrayreq = self._arraySource2D.request(s, along_through) return SegmentationEdgesItemRequest(arrayreq, self._layer, qrect, self._is_clickable)
def mergeWith(self, other): o = other if (not (self.mMapDocument == o.mMapDocument and self.mTarget == o.mTarget and o.mMergeable)): return False newRegion = o.mPaintedRegion.subtracted(self.mPaintedRegion) combinedRegion = self.mPaintedRegion.united(o.mPaintedRegion) bounds = QRect(self.mX, self.mY, self.mSource.width(), self.mSource.height()) combinedBounds = combinedRegion.boundingRect() # Resize the erased tiles and source layers when necessary if (bounds != combinedBounds): shift = bounds.topLeft() - combinedBounds.topLeft() self.mErased.resize(combinedBounds.size(), shift) self.mSource.resize(combinedBounds.size(), shift) mX = combinedBounds.left() self.mY = combinedBounds.top() self.mPaintedRegion = combinedRegion # Copy the painted tiles from the other command over pos = QPoint(o.mX, o.mY) - combinedBounds.topLeft() self.mSource.merge(pos, o.mSource) # Copy the newly erased tiles from the other command over for rect in newRegion.rects(): for y in range(rect.top(), rect.bottom()+1): for x in range(rect.left(), rect.right()+1): self.mErased.setCell(x - mX, y - self.mY, o.mErased.cellAt(x - o.mX, y - o.mY)) return True
def resize_completion(self): """Adjust completion according to config.""" if not self._completion.isVisible(): # It doesn't make sense to resize the completion as long as it's # not shown anyways. return # Get the configured height/percentage. confheight = str(config.get("completion", "height")) if confheight.endswith("%"): perc = int(confheight.rstrip("%")) height = self.height() * perc / 100 else: height = int(confheight) # Shrink to content size if needed and shrinking is enabled if config.get("completion", "shrink"): contents_height = ( self._completion.viewportSizeHint().height() + self._completion.horizontalScrollBar().sizeHint().height() ) if contents_height <= height: height = contents_height else: contents_height = -1 # hpoint now would be the bottom-left edge of the widget if it was on # the top of the main window. topleft_y = self.height() - self.status.height() - height topleft_y = qtutils.check_overflow(topleft_y, "int", fatal=False) topleft = QPoint(0, topleft_y) bottomright = self.status.geometry().topRight() rect = QRect(topleft, bottomright) log.misc.debug("completion rect: {}".format(rect)) if rect.isValid(): self._completion.setGeometry(rect)
def __redrawColorLabel(self, label, lc, uc): pixmap = QPixmap(101, 26) painter = QPainter(pixmap) lowerColorRect = QRect(0, 0, 50, 25) upperColorRect = QRect(50, 0, 50, 25) font = QFont("Times", 11) painter.setFont(font) painter.setPen(Qt.black) painter.setBrush(lc) painter.drawRect(lowerColorRect) lgray = lc.red() + lc.green() + lc.blue() painter.setPen(self.invert(lc)) painter.drawText(lowerColorRect.translated(8, 2), 0, str(lgray)) painter.setPen(Qt.black) painter.setBrush(uc) painter.drawRect(upperColorRect) ugray = uc.red() + uc.green() + uc.blue() painter.setPen(self.invert(uc)) painter.drawText(upperColorRect.translated(8, 2), 0, str(ugray)) del painter label.setPixmap(pixmap)
def mouseReleaseEvent(self, event): self.rubberBand.hide() zoreRect = QRect(self.origin, event.pos()).normalized() pixmapSize = self.pixmap().size() pixX1 = zoreRect.x() pixX2 = zoreRect.x() + zoreRect.width() pixY1 = zoreRect.y() pixY2 = zoreRect.y() + zoreRect.height() width = pixmapSize.width() height = pixmapSize.height() x1 = pixX1/width x1 = x1 if x1 >= 0.0 else 0.0 x1 = x1 if x1 <= 1.0 else 1.0 y1 = pixY1/height y1 = y1 if y1 >= 0.0 else 0.0 y1 = y1 if y1 <= 1.0 else 1.0 x2 = pixX2/width x2 = x2 if x2 >= 0.0 else 0.0 x2 = x2 if x2 <= 1.0 else 1.0 y2 = pixY2/height y2 = y2 if y2 >= 0.0 else 0.0 y2 = y2 if y2 <= 1.0 else 1.0 rect = QRect(min(pixX1, pixX2), min(pixY1, pixY2), abs(pixX1- pixX2), abs(pixY1- pixY2)) selectedImg = self.pixmap().copy(rect) self.areaSelected.emit(min(x1, x2), min(y1, y2), np.abs(x1-x2), np.abs(y1-y2), selectedImg)
def paintEvent(self, event): """Qt method override to paint a custom image on the Widget.""" super(FigureCanvas, self).paintEvent(event) qp = QPainter() qp.begin(self) # Prepare paint rect : fw = self.frameWidth() rect = QRect(0 + fw, 0 + fw, self.size().width() - 2 * fw, self.size().height() - 2 * fw) # Check/update image buffer : qpix2print = None for qpix in self.qpix_buff: if qpix.size().width() == rect.width(): qpix2print = qpix break if qpix2print is None: qpix2print = self.img.scaledToWidth( rect.width(), mode=Qt.SmoothTransformation) self.qpix_buff.append(qpix2print) # Draw pixmap : # qp.setRenderHint(QPainter.Antialiasing, True) qp.drawPixmap(rect, qpix2print) qp.end()
def _rect_on_view_js(self, adjust_zoom): """Javascript implementation for rect_on_view.""" rects = self._elem.evaluateJavaScript("this.getClientRects()") if rects is None: # pragma: no cover # Depending on unknown circumstances, this might not work with JS # disabled in QWebSettings: # https://github.com/The-Compiler/qutebrowser/issues/1641 return None text = utils.compact_text(self._elem.toOuterXml(), 500) log.hints.vdebug("Client rectangles of element '{}': {}".format( text, rects)) for i in range(int(rects.get("length", 0))): rect = rects[str(i)] width = rect.get("width", 0) height = rect.get("height", 0) if width > 1 and height > 1: # fix coordinates according to zoom level zoom = self._elem.webFrame().zoomFactor() if not config.get('ui', 'zoom-text-only') and adjust_zoom: rect["left"] *= zoom rect["top"] *= zoom width *= zoom height *= zoom rect = QRect(rect["left"], rect["top"], width, height) frame = self._elem.webFrame() while frame is not None: # Translate to parent frames' position (scroll position # is taken care of inside getClientRects) rect.translate(frame.geometry().topLeft()) frame = frame.parentFrame() return rect return None
def resize_completion(self): """Adjust completion according to config.""" # Get the configured height/percentage. confheight = str(config.get('completion', 'height')) if confheight.endswith('%'): perc = int(confheight.rstrip('%')) height = self.height() * perc / 100 else: height = int(confheight) # Shrink to content size if needed and shrinking is enabled if config.get('completion', 'shrink'): contents_height = ( self._completion.viewportSizeHint().height() + self._completion.horizontalScrollBar().sizeHint().height()) if contents_height <= height: height = contents_height else: contents_height = -1 # hpoint now would be the bottom-left edge of the widget if it was on # the top of the main window. topleft_y = self.height() - self.status.height() - height topleft_y = qtutils.check_overflow(topleft_y, 'int', fatal=False) topleft = QPoint(0, topleft_y) bottomright = self.status.geometry().topRight() rect = QRect(topleft, bottomright) if rect.isValid(): self._completion.setGeometry(rect)
def paint(self, painter, option, index): extra = index.data(Qt.UserRole + 1) if not extra: return QStyledItemDelegate.paint(self, painter, option, index) else: if option.state & QStyle.State_Selected: painter.fillRect(option.rect, option.palette.color(QPalette.Inactive, QPalette.Highlight)) title = index.data() extra = " - {}".format(extra) painter.drawText(option.rect, Qt.AlignLeft, title) fm = QFontMetrics(option.font) w = fm.width(title) r = QRect(option.rect) r.setLeft(r.left() + w) painter.save() if option.state & QStyle.State_Selected: painter.setPen(QColor(S.highlightedTextLight)) else: painter.setPen(QColor(S.textLight)) painter.drawText(r, Qt.AlignLeft, extra) painter.restore()
def updateStatusBar(self): if self._index: item = self._index.internalPointer() wc = item.data(Outline.wordCount.value) goal = item.data(Outline.goal.value) pg = item.data(Outline.goalPercentage.value) if goal: rect = self.lblProgress.geometry() rect = QRect(QPoint(0, 0), rect.size()) self.px = QPixmap(rect.size()) self.px.fill(Qt.transparent) p = QPainter(self.px) drawProgress(p, rect, pg, 2) p.end() self.lblProgress.setPixmap(self.px) self.lblWC.setText(self.tr("{} words / {}").format(wc, goal)) else: self.lblProgress.hide() self.lblWC.setText(self.tr("{} words").format(wc)) self.locker.setWordCount(wc) # If there's a goal, then we update the locker target's number of word accordingly # (also if there is a word count, we deduce it. if goal and not self.locker.isLocked(): if wc and goal - wc > 0: self.locker.spnWordTarget.setValue(goal - wc) elif not wc: self.locker.spnWordTarget.setValue(goal)
def test_invalid_frame_geometry(self, stubs): """Test with an invalid frame geometry.""" rect = QRect(0, 0, 0, 0) assert not rect.isValid() frame = stubs.FakeWebFrame(rect) elem = get_webelem(QRect(0, 0, 10, 10), frame) assert not elem.is_visible(frame)
def draw_lines(self, painter, option, rect, index): padding = 4 model = index.model() lineno = model.data(index, Qt.UserRole) if lineno < 1: return 0 is_selected = option.state & QStyle.State_Selected lineno_text = str(lineno) font_width = painter.fontMetrics().width(lineno_text) lineno_width = padding + font_width + padding lineno_rect = QRect(rect) lineno_rect.setWidth(lineno_width) lineno_rect.setX(0) color_group = QPalette.Normal if not option.state & QStyle.State_Active: color_group = QPalette.Inactive elif not option.state & QStyle.State_Enabled: color_group = QPalette.Disabled if is_selected: brush = option.palette.brush(color_group, QPalette.Highlight) else: brush = option.palette.color(color_group, QPalette.Base).darker(111) painter.fillRect(lineno_rect, brush) opt = option opt.font = settings.FONT # FIXME: performance # opt.displayAlignment = Qt.AlignRight | Qt.AlignVCenter opt.palette.setColor(color_group, QPalette.Text, Qt.darkGray) self.drawDisplay(painter, opt, lineno_rect, lineno_text) return lineno_width
def __init__(self, parent, persepolis_setting): super().__init__(parent) self.persepolis_setting = persepolis_setting # set ui direction ui_direction = self.persepolis_setting.value('ui_direction') if ui_direction == 'rtl': self.setLayoutDirection(Qt.RightToLeft) elif ui_direction in 'ltr': self.setLayoutDirection(Qt.LeftToRight) # set size self.resize(QSize(400, 80)) self.setFixedWidth(400) # show this widget as ToolTip widget self.setWindowFlags(Qt.ToolTip) # find bottom right position bottom_right_screen = QDesktopWidget().availableGeometry().bottomRight() bottom_right_notification = QRect(QPoint(0,0), QSize(410, 120)) bottom_right_notification.moveBottomRight(bottom_right_screen) self.move(bottom_right_notification.topLeft()) # get persepolis icon path icons = ':/' + \ str(self.persepolis_setting.value('settings/icons')) + '/' notification_horizontalLayout = QHBoxLayout(self) # persepolis icon svgWidget = QtSvg.QSvgWidget(':/persepolis.svg') svgWidget.setFixedSize(QSize(64, 64)) notification_horizontalLayout.addWidget(svgWidget) notification_verticalLayout = QVBoxLayout() # 2 labels for notification messages self.label1 = QLabel(self) self.label1.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self.label1.setStyleSheet("font-weight: bold") self.label1.setWordWrap(True) self.label2 = QLabel(self) self.label2.setWordWrap(True) self.label2.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) notification_verticalLayout.addWidget(self.label1) notification_verticalLayout.addWidget(self.label2) notification_horizontalLayout.addLayout(notification_verticalLayout)
def apply_selection(self, rect: QRect): self.selection_active = False self.group.set_position(rect.x(), rect.y()) self.group.set_size(rect.width(), rect.height()) if self.rect_was_displayed and self.visibility_checkbox.isChecked(): self.__add_roi_rect() self.rect_was_displayed = False
def merge(self, pos, layer): # Determine the overlapping area area = QRect(pos, QSize(layer.width(), layer.height())) area &= QRect(0, 0, self.width(), self.height()) for y in range(area.top(), area.bottom()+1): for x in range(area.left(), area.right()+1): cell = layer.cellAt(x - pos.x(), y - pos.y()) if (not cell.isEmpty()): self.setCell(x, y, cell)
def drawName(self, p): a = self.r * sqrt(2) sz = self.frameGeometry().size() tq = QRect(sz.width()/2 - a/2, sz.height()/2 - a/2, a, a) ## text_scale -- has effect only untill you fit bbox tsz = tq.size() * float(self.sty['Text']['scale']) base.adjustFontSize(self, self.name, tsz) p.setPen(QtGui.QColor(*list(self.sty['Text']['color']))) p.drawText(tq, Qt.AlignCenter, self.name)
def destinationsRect(self, destinations): """Return the rectangle containing all destinations.""" layout = self.view.surface().pageLayout() rect = QRect() for dest in destinations: for pageNum, r in dest: rect = rect.united(layout[pageNum].linkRect(r.normalized())) # not larger than viewport rect.setSize(rect.size().boundedTo(self.view.viewport().size())) return rect
def drawProgress(painter, rect, progress, radius=0): painter.setPen(Qt.NoPen) painter.setBrush(QColor("#dddddd")) painter.drawRoundedRect(rect, radius, radius) painter.setBrush(QBrush(colorFromProgress(progress))) r2 = QRect(rect) r2.setWidth(r2.width() * min(progress, 1)) painter.drawRoundedRect(r2, radius, radius)
def _tab_layout(self, opt): """Compute the text/icon rect from the opt rect. This is based on Qt's QCommonStylePrivate::tabLayout (qtbase/src/widgets/styles/qcommonstyle.cpp) as we can't use the private implementation. Args: opt: QStyleOptionTab Return: A (text_rect, icon_rect) tuple (both QRects). """ padding = self.pixelMetric(PM_TabBarPadding, opt) icon_rect = QRect() text_rect = QRect(opt.rect) qtutils.ensure_valid(text_rect) indicator_width = config.get('tabs', 'indicator-width') text_rect.adjust(padding, 0, 0, 0) if indicator_width != 0: text_rect.adjust(indicator_width + config.get('tabs', 'indicator-space'), 0, 0, 0) if not opt.icon.isNull(): icon_rect = self._get_icon_rect(opt, text_rect) text_rect.adjust(icon_rect.width() + padding, 0, 0, 0) text_rect = self._style.visualRect(opt.direction, opt.rect, text_rect) return (text_rect, icon_rect)
def _paint_icon(self, iconic, painter, rect, mode, state, options): """Paint a single icon.""" painter.save() color = options['color'] char = options['char'] color_options = { QIcon.On: { QIcon.Normal: (options['color_on'], options['on']), QIcon.Disabled: (options['color_on_disabled'], options['on_disabled']), QIcon.Active: (options['color_on_active'], options['on_active']), QIcon.Selected: (options['color_on_selected'], options['on_selected']) }, QIcon.Off: { QIcon.Normal: (options['color_off'], options['off']), QIcon.Disabled: (options['color_off_disabled'], options['off_disabled']), QIcon.Active: (options['color_off_active'], options['off_active']), QIcon.Selected: (options['color_off_selected'], options['off_selected']) } } color, char = color_options[state][mode] painter.setPen(QColor(color)) # A 16 pixel-high icon yields a font size of 14, which is pixel perfect # for font-awesome. 16 * 0.875 = 14 # The reason why the glyph size is smaller than the icon size is to # account for font bearing. draw_size = 0.875 * qRound(rect.height() * options['scale_factor']) prefix = options['prefix'] # Animation setup hook animation = options.get('animation') if animation is not None: animation.setup(self, painter, rect) painter.setFont(iconic.font(prefix, draw_size)) if 'offset' in options: rect = QRect(rect) rect.translate(options['offset'][0] * rect.width(), options['offset'][1] * rect.height()) painter.setOpacity(options.get('opacity', 1.0)) painter.drawText(rect, Qt.AlignCenter | Qt.AlignVCenter, char) painter.restore()
def drawProgress(painter, rect, progress, radius=0): from manuskript.ui import style as S painter.setPen(Qt.NoPen) painter.setBrush(QColor(S.base)) # "#dddddd" painter.drawRoundedRect(rect, radius, radius) painter.setBrush(QBrush(colorFromProgress(progress))) r2 = QRect(rect) r2.setWidth(r2.width() * min(progress, 1)) painter.drawRoundedRect(r2, radius, radius)
def scene_item_rects_updated(self, items): """The user moved or resized items in the scene """ debug_print('GraphicsItemView.item_rects_updated') for index, item in zip(self.indexes_of_items(items), items): # item.sceneBoundingRect() is the items rects in the correct # coordinates system debug_print('Row [{0}] updated'.format(index.row())) rect = item.sceneBoundingRect() # Cumbersome conversion to ints rect = QRect(rect.left(), rect.top(), rect.width(), rect.height()) self.model().setData(index, rect, RectRole)
def paintEvent(self, ev): image = self.viewer.image() painter = QPainter(self) if self.size() == image.size(): painter.drawImage(ev.rect(), image, ev.rect()) else: s = image.size() s.scale(self.size(), Qt.KeepAspectRatio) r = QRect() r.setSize(s) r.moveCenter(self.rect().center()) painter.drawPixmap(r, self.viewer.pixmap(s))
def calculateLogicalRect(self, physicalRect): gridX = self.parent().width() / 40 gridY = self.parent().height() / 30 logicalRect = QRect() logicalRect.setTop(round(physicalRect.top() / gridY)) logicalRect.setLeft(round(physicalRect.left() / gridX)) logicalRect.setWidth(round(physicalRect.width() / gridX)) logicalRect.setHeight(round(physicalRect.height() / gridY)) return logicalRect
def subcontrolOnPosition(self, position) : element = QStyle.SubControl() rect = QRect() rect = self._style.subControlRect(QStyle.CC_Slider, self._options.getUpperHandleOptions(), QStyle.SC_SliderHandle); if rect.contains(position) : return SubControl.UpperHandle; rect = self._style.subControlRect(QStyle.CC_Slider, self._options.getLowerHandleOptions(), QStyle.SC_SliderHandle); if rect.contains(position) : return SubControl.LowerHandle; rect = self._style.subControlRect(QStyle.CC_Slider, self._options.getGrooveOptions(), QStyle.SC_SliderGroove); if rect.contains(position) : return SubControl.Groove; return SubControl.No;
def _rect_on_view_python(self, elem_geometry): """Python implementation for rect_on_view.""" if elem_geometry is None: geometry = self._elem.geometry() else: geometry = elem_geometry frame = self._elem.webFrame() rect = QRect(geometry) while frame is not None: rect.translate(frame.geometry().topLeft()) rect.translate(frame.scrollPosition() * -1) frame = frame.parentFrame() return rect
def __init__(self, mainWindow, container): super().__init__(container, objectName='paramsGroup') self.mainWindow = mainWindow self.setGeometry(QRect(10, 0, 341, 191)) self.setTitle('Parameters') self.colorList = importColors(self.mainWindow.path + 'include/colors.xml') self.beginLabel = QLabel(self, objectName='beginLabel') self.beginLabel.setGeometry(QRect(10, 20, 91, 21)) self.beginLabel.setText('• Color 1 (Begin) :') self.endLabel = QLabel(self, objectName='endLabel') self.endLabel.setGeometry(QRect(10, 50, 91, 21)) self.endLabel.setText('• Color 2 (End) :') self.velocityLabel = QLabel(self, objectName='velocityLabel') self.velocityLabel.setGeometry(QRect(10, 80, 61, 21)) self.velocityLabel.setText('• Velocity :') self.levelLabel = QLabel(self, objectName='levelLabel') self.levelLabel.setGeometry(QRect(10, 110, 61, 21)) self.levelLabel.setText('• Level :') self.beginComboBox = QComboBox(self, objectName='beginComboBox') self.beginComboBox.setGeometry(QRect(100, 20, 81, 22)) self.endComboBox = QComboBox(self, objectName='endComboBox') self.endComboBox.setGeometry(QRect(100, 50, 81, 22)) for color in self.colorList: self.beginComboBox.addItem(color['name']) self.endComboBox.addItem(color['name']) self.endComboBox.setCurrentIndex(1) self.velocitySpinBox = QSpinBox(self, objectName='velocitySpinBox') self.velocitySpinBox.setGeometry(QRect(70, 80, 91, 22)) self.velocitySpinBox.setMaximum(5) self.velocitySpinBox.setValue(1) self.velocitySpinBox.setSuffix(' pixel/move') self.levelComboBox = QComboBox(self, objectName='levelComboBox') self.levelComboBox.setGeometry(QRect(70, 110, 81, 22)) self.levelComboBox.addItem('Easy') self.levelComboBox.addItem('Medium') self.levelComboBox.addItem('Hard') self.levelSpinBox = QSpinBox(self, objectName='levelSpinBox') self.levelSpinBox.setGeometry(QRect(160, 110, 61, 22)) self.levelSpinBox.setMinimum(1) self.levelSpinBox.setMaximum(3) self.actionButton = QPushButton(self, objectName='actionButton') self.actionButton.setGeometry(QRect(100, 150, 141, 31)) self.actionButton.setText('Start game') self.velocitySpinBox.valueChanged.connect(self.changed_velocitySpinBox) self.actionButton.clicked.connect(self.clicked_actionButton)
def paintEvent(self, e): self.painter.begin(self) # 绘制图片内容 self.painter.drawPixmap(self.rect(), self.pixmap, self.pmapShowAreaRect) # 绘制图片区域预览 self.painter.setPen(QColor(0, 0, 0)) scale = min(self.width() / self.pixmap.width() / 5, self.height() / self.pixmap.height() / 5) self.pmapPreRect = QRect(0, 0, self.pixmap.width() * scale, self.pixmap.height() * scale) margin = int(min(self.width(), self.height()) / 16) self.pmapPreRect.moveTopRight(QPoint(self.width() - margin, margin)) self.painter.drawRect(self.pmapPreRect) # 绘制图片展示区域预览 self.painter.setPen(QColor(255, 0, 0)) pmapprerect = self.pmapPreRect.getRect() pmapshowarearect = self.pmapShowAreaRect.getRect() x = pmapprerect[0] + self.pmapPreRect.width( ) * pmapshowarearect[0] / self.pixmap.width() y = pmapprerect[1] + self.pmapPreRect.height( ) * pmapshowarearect[1] / self.pixmap.height() w = scale * self.pmapShowAreaRect.width() h = scale * self.pmapShowAreaRect.height() self.pmapShowAreaPreRect = QRect(x, y, w, h) self.painter.drawRect(self.pmapShowAreaPreRect) self.dragAreaRect = QRect( self.pmapPreRect.x() - self.pmapShowAreaPreRect.width(), self.pmapPreRect.y() - self.pmapShowAreaPreRect.height(), self.pmapShowAreaPreRect.width() + self.pmapPreRect.width(), self.pmapShowAreaPreRect.height() + self.pmapPreRect.height()) # 绘制缩放中心点标线 self.painter.setPen(QColor(255, 0, 0)) self.painter.drawLine(self.width() / 3, self.height() / 2, self.width() / 3 * 2, self.height() / 2) self.painter.drawLine(self.width() / 2, self.height() / 3, self.width() / 2, self.height() / 3 * 2) # 绘制鼠标位置标线 if self.labeling: self.painter.setPen(QColor(0, 0, 0)) self.painter.drawLine(self.mousex, 0, self.mousex, self.height()) self.painter.drawLine(0, self.mousey, self.width(), self.mousey) # 绘制正在编辑中的label位置 if self.templabel: for i in range(int(len(self.templabel) / 2)): imagex, imagey = self.templabel[0 + 2 * i], self.templabel[1 + 2 * i] if self.pmapShowAreaRect.contains(imagex, imagey): widgetx, widgety = self.imageXY2WidgetXY(imagex, imagey) self.painter.setPen(QPen(Qt.red, 5)) self.painter.drawPoint(widgetx, widgety) pen = QPen(Qt.black, 2, Qt.SolidLine) pen.setStyle(Qt.DashDotDotLine) self.painter.setPen(pen) self.painter.drawLine(widgetx, 0, widgetx, self.height()) self.painter.drawLine(0, widgety, self.width(), widgety) # 绘制已标记内容 self.deleteRects.clear() self.textRects.clear() self.painter.setPen(QColor(168, 34, 3)) self.painter.setFont(QFont('Decorative', 12)) metrics = self.painter.fontMetrics() deleteRectWidth, deleteRectHeight = metrics.height( ) * 1.2, metrics.height() * 1.2 separatorheight = margin / 10 pmapprerect = self.pmapPreRect.getRect() topRightx, topRighty = self.width( ) - margin, pmapprerect[1] + pmapprerect[3] + margin / 4 for i in range(len(self.labels)): label = self.labels[i] # 绘制文字展示信息 text = label[4] deleteRect = QRect( topRightx - deleteRectWidth, topRighty + (deleteRectHeight + separatorheight) * i, deleteRectWidth, deleteRectHeight) self.painter.drawRect(deleteRect) self.painter.drawLine(deleteRect.topLeft(), deleteRect.bottomRight()) self.painter.drawLine(deleteRect.topRight(), deleteRect.bottomLeft()) self.deleteRects.append(deleteRect) deleterect = deleteRect.getRect() textWidth, textHeight = metrics.width(text), metrics.height() textRect = QRect(deleterect[0] - textWidth - metrics.height(), deleterect[1], textWidth + metrics.height(), deleterect[3]) self.painter.drawRect(textRect) self.painter.drawText(textRect, Qt.AlignCenter, text) self.textRects.append(textRect) # 在图片上绘制标签矩形框 labelPixmapX, labelPixmapY, labelPixmapWidth, labelPixmapHeight = label[: 4] labelPixmapRect = QRect(labelPixmapX, labelPixmapY, labelPixmapWidth, labelPixmapHeight) intersectedRect = self.pmapShowAreaRect.intersected( labelPixmapRect) if intersectedRect: pixmapTopLeftPoint, pixmapBottomRightPoint = intersectedRect.topLeft( ), intersectedRect.bottomRight() widgetTopLeftPointX, widgetTopLeftPointY = self.imageXY2WidgetXY( pixmapTopLeftPoint.x(), pixmapTopLeftPoint.y()) widgetTopLeftPoint = QPoint(widgetTopLeftPointX, widgetTopLeftPointY) widgetBottomRightPointX, widgetBottomRightPointY = self.imageXY2WidgetXY( pixmapBottomRightPoint.x(), pixmapBottomRightPoint.y()) widgetBottomRightPoint = QPoint(widgetBottomRightPointX, widgetBottomRightPointY) labelRect = QRect(widgetTopLeftPoint, widgetBottomRightPoint) self.painter.drawRect(labelRect) # 绘制标签名 labelrect = labelRect.getRect() textRect1 = QRect(labelrect[0], labelrect[1] - textHeight, textWidth, textHeight) # self.painter.drawRect(textRect1) self.painter.drawText(textRect1, Qt.AlignCenter, text) self.painter.end()
def resize_table(self): w = self.tableWidget.horizontalHeader().defaultSectionSize() h = self.tableWidget.verticalHeader().defaultSectionSize() self.tableWidget.setGeometry(QRect(0, 0, w * (self.n_col + 1), h * (self.n_row() + 1)))
def paintEvent(self, event): if not self.customStyle: return QGroupBox.paintEvent(self, event) p = QStylePainter(self) opt = QStyleOptionGroupBox() self.initStyleOption(opt) style = qApp.style() groupBox = opt # // Draw frame textRect = style.subControlRect(style.CC_GroupBox, opt, style.SC_GroupBoxLabel) checkBoxRect = style.subControlRect(style.CC_GroupBox, opt, style.SC_GroupBoxCheckBox) p.save() titleRect = style.subControlRect(style.CC_GroupBox, opt, style.SC_GroupBoxFrame) # r.setBottom(style.subControlRect(style.CC_GroupBox, opt, style.SC_GroupBoxContents).top()) titleRect.setHeight(textRect.height()) titleRect.moveTop(textRect.top()) p.setBrush(QBrush(QColor(S.highlightLight))) p.setPen(Qt.NoPen) p.drawRoundedRect(titleRect, 10, 10) p.restore() if groupBox.subControls & QStyle.SC_GroupBoxFrame: frame = QStyleOptionFrame() # frame.operator=(groupBox) frame.state = groupBox.state frame.features = groupBox.features frame.lineWidth = groupBox.lineWidth frame.midLineWidth = groupBox.midLineWidth frame.rect = style.subControlRect(style.CC_GroupBox, opt, style.SC_GroupBoxFrame) p.save() region = QRegion(groupBox.rect) if groupBox.text: ltr = groupBox.direction == Qt.LeftToRight finalRect = QRect() if groupBox.subControls & QStyle.SC_GroupBoxCheckBox: finalRect = checkBoxRect.united(textRect) finalRect.adjust(-4 if ltr else 0, 0, 0 if ltr else 4, 0) else: finalRect = textRect region -= QRegion(finalRect) p.setClipRegion(region) style.drawPrimitive(style.PE_FrameGroupBox, frame, p) p.restore() # // Draw title if groupBox.subControls & QStyle.SC_GroupBoxLabel and groupBox.text: # textColor = QColor(groupBox.textColor) # if textColor.isValid(): # p.setPen(textColor) # alignment = int(groupBox.textAlignment) # if not style.styleHint(QStyle.SH_UnderlineShortcut, opt): # alignment |= Qt.TextHideMnemonic # style.drawItemText(p, textRect, Qt.TextShowMnemonic | Qt.AlignHCenter | alignment, # groupBox.palette, groupBox.state & style.State_Enabled, groupBox.text, # QPalette.NoRole if textColor.isValid() else QPalette.WindowText) p.save() topt = QTextOption(Qt.AlignHCenter | Qt.AlignVCenter) f = QFont() f.setBold(True) p.setFont(f) p.setPen(QColor(S.highlightedTextDark)) p.drawText(QRectF(titleRect), groupBox.text.replace("&", ""), topt) p.restore() if groupBox.state & style.State_HasFocus: fropt = QStyleOptionFocusRect() # fropt.operator=(groupBox) fropt.state = groupBox.state fropt.rect = textRect style.drawPrimitive(style.PE_FrameFocusRect, fropt, p)
def test_scrolled(self, geometry, visible, stubs): scrolled_frame = stubs.FakeWebFrame(QRect(0, 0, 100, 100), scroll=QPoint(10, 10)) elem = get_webelem(geometry, scrolled_frame) assert elem._is_visible(scrolled_frame) == visible
def seed_img(self, is_seed=True): if is_seed: try: cseed = self.get_seed() except UserCancelled: return except InvalidPassword as e: self.d.show_error(str(e)) return if not cseed: self.d.show_message(_("This wallet has no seed")) return txt = cseed.upper() else: txt = self.txt.upper() img = QImage(self.SIZE[0], self.SIZE[1], QImage.Format_Mono) bitmap = QBitmap.fromImage(img, Qt.MonoOnly) bitmap.fill(Qt.white) painter = QPainter() painter.begin(bitmap) QFontDatabase.addApplicationFont( os.path.join(os.path.dirname(__file__), 'SourceSansPro-Bold.otf')) if len(txt) < 102: fontsize = 15 linespace = 15 max_letters = 17 max_lines = 6 max_words = 3 else: fontsize = 12 linespace = 10 max_letters = 21 max_lines = 9 max_words = int(max_letters / 4) font = QFont('Source Sans Pro', fontsize, QFont.Bold) font.setLetterSpacing(QFont.PercentageSpacing, 100) font.setPixelSize(fontsize) painter.setFont(font) seed_array = txt.split(' ') for n in range(max_lines): nwords = max_words temp_seed = seed_array[:nwords] while len(' '.join(map(str, temp_seed))) > max_letters: nwords = nwords - 1 temp_seed = seed_array[:nwords] painter.drawText( QRect(0, linespace * n, self.SIZE[0], self.SIZE[1]), Qt.AlignHCenter, ' '.join(map(str, temp_seed))) del seed_array[:nwords] painter.end() img = bitmap.toImage() if (self.rawnoise == False): self.make_rawnoise() self.make_cypherseed(img, self.rawnoise, False, is_seed) return img
COULEUR_NEUTRE = "Noir" ECHELLE = { 2: 3, 3: 5, 4: 7, 5: 9, 6: 11, 7: 13, 12: 3, 11: 5, 10: 7, 9: 9, 8: 11 } POSITION_neutre = [ QRect(50, 190, 41, 41), QRect(50, 240, 41, 41), QRect(50, 290, 41, 41) ] def lancer_de(de_a: QLabel, de_b: QLabel, de_c: QLabel, de_d: QLabel): """ Effectue un lance de dés et expose le résultat :return: possibilite : liste des 3 possibilités """ lancer_des = [rand.randrange(1, 7) for _ in range(4)] possibilite = [ (lancer_des[0] + lancer_des[1], lancer_des[2] + lancer_des[3]), (lancer_des[0] + lancer_des[2], lancer_des[1] + lancer_des[3]), (lancer_des[0] + lancer_des[3], lancer_des[2] + lancer_des[1])
def resizeEvent(self, event): super().resizeEvent(event) cr = self.contentsRect() self.lineNumberArea.setGeometry(QRect(cr.left(), cr.top(), self.lineNumberAreaWidth(), cr.height()))
def open_roi_selection(self): self.roiWindow = CameraROI(self.cam) self.roiWindow.setGeometry(QRect(100, 100, 600, 600)) self.roiWindow.show()
def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(400, 294) self.line_2 = QFrame(Dialog) self.line_2.setGeometry(QRect(40, 230, 321, 16)) self.line_2.setFrameShape(QFrame.HLine) self.line_2.setFrameShadow(QFrame.Sunken) self.line_2.setObjectName("line_2") self.layoutWidget = QWidget(Dialog) self.layoutWidget.setGeometry(QRect(100, 120, 56, 85)) self.layoutWidget.setObjectName("layoutWidget") self.verticalLayout = QVBoxLayout(self.layoutWidget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.useTime = QLabel(self.layoutWidget) font = QFont() font.setFamily(".PingFang SC0") font.setPointSize(16) self.useTime.setFont(font) self.useTime.setObjectName("useTime") self.verticalLayout.addWidget(self.useTime) self.useCount = QLabel(self.layoutWidget) font = QFont() font.setFamily(".PingFang SC0") font.setPointSize(16) self.useCount.setFont(font) self.useCount.setObjectName("useCount") self.verticalLayout.addWidget(self.useCount) self.label = QLabel(Dialog) self.label.setGeometry(QRect(70, 50, 241, 51)) font = QFont() font.setFamily(".PingFang SC0") font.setPointSize(16) self.label.setFont(font) self.label.setObjectName("label") self.layoutWidget_2 = QWidget(Dialog) self.layoutWidget_2.setGeometry(QRect(60, 250, 274, 30)) self.layoutWidget_2.setObjectName("layoutWidget_2") self.gridLayout_2 = QGridLayout(self.layoutWidget_2) self.gridLayout_2.setContentsMargins(0, 0, 0, 0) self.gridLayout_2.setObjectName("gridLayout_2") self.next = QPushButton(self.layoutWidget_2) self.next.setObjectName("next") self.gridLayout_2.addWidget(self.next, 0, 0, 1, 1) self.quit = QPushButton(self.layoutWidget_2) self.quit.setObjectName("quit") self.gridLayout_2.addWidget(self.quit, 0, 2, 1, 1) self.label_2 = QLabel(self.layoutWidget_2) self.label_2.setText("") self.label_2.setObjectName("label_2") self.gridLayout_2.addWidget(self.label_2, 0, 1, 1, 1) self.line = QFrame(Dialog) self.line.setGeometry(QRect(40, 20, 321, 16)) self.line.setFrameShape(QFrame.HLine) self.line.setFrameShadow(QFrame.Sunken) self.line.setObjectName("line") self.line_4 = QFrame(Dialog) self.line_4.setGeometry(QRect(350, 30, 16, 211)) self.line_4.setFrameShape(QFrame.VLine) self.line_4.setFrameShadow(QFrame.Sunken) self.line_4.setObjectName("line_4") self.line_3 = QFrame(Dialog) self.line_3.setGeometry(QRect(30, 30, 16, 211)) self.line_3.setFrameShape(QFrame.VLine) self.line_3.setFrameShadow(QFrame.Sunken) self.line_3.setObjectName("line_3") self.retranslateUi(Dialog) QMetaObject.connectSlotsByName(Dialog)
def _set_default_geometry(self): """Set some sensible default geometry.""" self.setGeometry(QRect(50, 50, 800, 600))
def run(self): cap = cv2.VideoCapture(0) # 0 init; 1 start; 2 end flag = 0 # times times = 0 # record last_result = [] seg = Segmentation() seg.load_model() while True: ret, frame = cap.read() if ret: seg.add_img(frame) seg.hough_circles() if seg.check_circles(): seg.get_circle_pixel(10) result = list(seg.get_colors()) result.sort() self.app.ui.pushButton.setText( QCoreApplication.translate(u"recogination", ', '.join(result))) if times >= 5: self.app.ui.pushButton_2.setText( QCoreApplication.translate(u"recogination", '检测完成,请移走餐盘')) flag = 2 else: self.app.ui.pushButton_2.setText( QCoreApplication.translate(u"recogination", '检测中...')) flag = 1 self.app.ui.price.display(self.price(result)) seg.draw_circles() if result == last_result: times += 1 else: times = 0 last_result = result else: self.app.ui.pushButton.setText( QCoreApplication.translate(u"recogination", 'prepare for detecting')) self.app.ui.pushButton_2.setText( QCoreApplication.translate(u"recogination", '请放入餐盘...')) self.app.ui.price.display(0) times = 0 last_result = [] if flag == 2: '''jie suan''' rgbImage = cv2.cvtColor(seg.img_rgb, cv2.COLOR_BGR2RGB) convertToQtFormat = QImage(rgbImage.data, rgbImage.shape[1], rgbImage.shape[0], QImage.Format_RGB888) width, height = self.adjust_scale(rgbImage) p = convertToQtFormat.scaled(width, height) self.app.label.setGeometry( QRect(0, 0, self.app.ui.frame.width(), self.app.ui.frame.height())) self.changePixmap.emit(p)
def get_rect(self, name, default=None): r = self.get_value(name, default) if r is not None: return QRect(*r) else: return None
def paintEvent(self, e): super(LabeledSlider, self).paintEvent(e) style = self.slider.style() painter = QPainter(self) st_slider = QStyleOptionSlider() st_slider.initFrom(self.slider) st_slider.orientation = self.slider.orientation() length = style.pixelMetric(QStyle.PM_SliderLength, st_slider, self.slider) available = style.pixelMetric(QStyle.PM_SliderSpaceAvailable, st_slider, self.slider) for v, v_str in self.levels: # get the size of the label rect = painter.drawText(QRect(), Qt.TextDontPrint, str(v_str)) if self.slider.orientation() == Qt.Horizontal: # I assume the offset is half the length of slider, therefore # + length//2 x_loc = QStyle.sliderPositionFromValue( self.slider.minimum(), self.slider.maximum(), v, available) + length // 2 # left bound of the text = center - half of text width + L_margin left = x_loc - rect.width() // 2 + self.left_margin bottom = self.rect().bottom() # enlarge margins if clipping if v == self.slider.minimum(): if left <= 0: self.left_margin = rect.width() // 2 - x_loc if self.bottom_margin <= rect.height(): self.bottom_margin = rect.height() self.layout.setContentsMargins(self.left_margin, self.top_margin, self.right_margin, self.bottom_margin) if v == self.slider.maximum( ) and rect.width() // 2 >= self.right_margin: self.right_margin = rect.width() // 2 self.layout.setContentsMargins(self.left_margin, self.top_margin, self.right_margin, self.bottom_margin) else: y_loc = QStyle.sliderPositionFromValue(self.slider.minimum(), self.slider.maximum(), v, available, upsideDown=True) bottom = y_loc + length // 2 + rect.height( ) // 2 + self.top_margin - 3 # there is a 3 px offset that I can't attribute to any metric left = self.left_margin - rect.width() if left <= 0: self.left_margin = rect.width() + 2 self.layout.setContentsMargins(self.left_margin, self.top_margin, self.right_margin, self.bottom_margin) pos = QPoint(left, bottom) painter.drawText(pos, str(v_str)) return
def overlay_marks(self, img, is_cseed=False, calibration_sheet=False): border_color = Qt.white base_img = QImage(self.f_size.width(), self.f_size.height(), QImage.Format_ARGB32) base_img.fill(border_color) img = QImage(img) painter = QPainter() painter.begin(base_img) total_distance_h = round(base_img.width() / self.abstand_v) dist_v = round(total_distance_h) / 2 dist_h = round(total_distance_h) / 2 img = img.scaledToWidth(base_img.width() - (2 * (total_distance_h))) painter.drawImage(total_distance_h, total_distance_h, img) #frame around image pen = QPen(Qt.black, 2) painter.setPen(pen) #horz painter.drawLine(0, total_distance_h, base_img.width(), total_distance_h) painter.drawLine(0, base_img.height() - (total_distance_h), base_img.width(), base_img.height() - (total_distance_h)) #vert painter.drawLine(total_distance_h, 0, total_distance_h, base_img.height()) painter.drawLine(base_img.width() - (total_distance_h), 0, base_img.width() - (total_distance_h), base_img.height()) #border around img border_thick = 6 Rpath = QPainterPath() Rpath.addRect( QRectF((total_distance_h) + (border_thick / 2), (total_distance_h) + (border_thick / 2), base_img.width() - ((total_distance_h) * 2) - ((border_thick) - 1), (base_img.height() - ((total_distance_h)) * 2) - ((border_thick) - 1))) pen = QPen(Qt.black, border_thick) pen.setJoinStyle(Qt.MiterJoin) painter.setPen(pen) painter.drawPath(Rpath) Bpath = QPainterPath() Bpath.addRect( QRectF((total_distance_h), (total_distance_h), base_img.width() - ((total_distance_h) * 2), (base_img.height() - ((total_distance_h)) * 2))) pen = QPen(Qt.black, 1) painter.setPen(pen) painter.drawPath(Bpath) pen = QPen(Qt.black, 1) painter.setPen(pen) painter.drawLine(0, base_img.height() / 2, total_distance_h, base_img.height() / 2) painter.drawLine(base_img.width() / 2, 0, base_img.width() / 2, total_distance_h) painter.drawLine(base_img.width() - total_distance_h, base_img.height() / 2, base_img.width(), base_img.height() / 2) painter.drawLine(base_img.width() / 2, base_img.height(), base_img.width() / 2, base_img.height() - total_distance_h) #print code f_size = 37 QFontDatabase.addApplicationFont( os.path.join(os.path.dirname(__file__), 'DejaVuSansMono-Bold.ttf')) font = QFont("DejaVu Sans Mono", f_size - 11, QFont.Bold) font.setPixelSize(35) painter.setFont(font) if not calibration_sheet: if is_cseed: #its a secret painter.setPen(QPen(Qt.black, 1, Qt.DashDotDotLine)) painter.drawLine(0, dist_v, base_img.width(), dist_v) painter.drawLine(dist_h, 0, dist_h, base_img.height()) painter.drawLine(0, base_img.height() - dist_v, base_img.width(), base_img.height() - (dist_v)) painter.drawLine(base_img.width() - (dist_h), 0, base_img.width() - (dist_h), base_img.height()) painter.drawImage( ((total_distance_h)) + 11, ((total_distance_h)) + 11, QImage(icon_path('electrumb.png')).scaledToWidth( 2.1 * (total_distance_h), Qt.SmoothTransformation)) painter.setPen(QPen(Qt.white, border_thick * 8)) painter.drawLine( base_img.width() - ((total_distance_h)) - (border_thick * 8) / 2 - (border_thick / 2) - 2, (base_img.height() - ((total_distance_h))) - ((border_thick * 8) / 2) - (border_thick / 2) - 2, base_img.width() - ((total_distance_h)) - (border_thick * 8) / 2 - (border_thick / 2) - 2 - 77, (base_img.height() - ((total_distance_h))) - ((border_thick * 8) / 2) - (border_thick / 2) - 2) painter.setPen(QColor(0, 0, 0, 255)) painter.drawText( QRect( 0, base_img.height() - 107, base_img.width() - total_distance_h - border_thick - 11, base_img.height() - total_distance_h - border_thick), Qt.AlignRight, self.versioned_seed.version + '_' + self.versioned_seed.checksum) painter.end() else: # revealer painter.setPen(QPen(border_color, 17)) painter.drawLine(0, dist_v, base_img.width(), dist_v) painter.drawLine(dist_h, 0, dist_h, base_img.height()) painter.drawLine(0, base_img.height() - dist_v, base_img.width(), base_img.height() - (dist_v)) painter.drawLine(base_img.width() - (dist_h), 0, base_img.width() - (dist_h), base_img.height()) painter.setPen(QPen(Qt.black, 2)) painter.drawLine(0, dist_v, base_img.width(), dist_v) painter.drawLine(dist_h, 0, dist_h, base_img.height()) painter.drawLine(0, base_img.height() - dist_v, base_img.width(), base_img.height() - (dist_v)) painter.drawLine(base_img.width() - (dist_h), 0, base_img.width() - (dist_h), base_img.height()) logo = QImage(icon_path('revealer_c.png')).scaledToWidth( 1.3 * (total_distance_h)) painter.drawImage((total_distance_h) + (border_thick), ((total_distance_h)) + (border_thick), logo, Qt.SmoothTransformation) #frame around logo painter.setPen(QPen(Qt.black, border_thick)) painter.drawLine( total_distance_h + border_thick, total_distance_h + logo.height() + 3 * (border_thick / 2), total_distance_h + logo.width() + border_thick, total_distance_h + logo.height() + 3 * (border_thick / 2)) painter.drawLine( logo.width() + total_distance_h + 3 * (border_thick / 2), total_distance_h + (border_thick), total_distance_h + logo.width() + 3 * (border_thick / 2), total_distance_h + logo.height() + (border_thick)) #frame around code/qr qr_size = 179 painter.drawLine((base_img.width() - ((total_distance_h)) - (border_thick / 2) - 2) - qr_size, (base_img.height() - ((total_distance_h))) - ((border_thick * 8)) - (border_thick / 2) - 2, (base_img.width() / 2 + (total_distance_h / 2) - border_thick - (border_thick * 8) / 2) - qr_size, (base_img.height() - ((total_distance_h))) - ((border_thick * 8)) - (border_thick / 2) - 2) painter.drawLine( (base_img.width() / 2 + (total_distance_h / 2) - border_thick - (border_thick * 8) / 2) - qr_size, (base_img.height() - ((total_distance_h))) - ((border_thick * 8)) - (border_thick / 2) - 2, base_img.width() / 2 + (total_distance_h / 2) - border_thick - (border_thick * 8) / 2 - qr_size, ((base_img.height() - ((total_distance_h))) - (border_thick / 2) - 2)) painter.setPen(QPen(Qt.white, border_thick * 8)) painter.drawLine( base_img.width() - ((total_distance_h)) - (border_thick * 8) / 2 - (border_thick / 2) - 2, (base_img.height() - ((total_distance_h))) - ((border_thick * 8) / 2) - (border_thick / 2) - 2, base_img.width() / 2 + (total_distance_h / 2) - border_thick - qr_size, (base_img.height() - ((total_distance_h))) - ((border_thick * 8) / 2) - (border_thick / 2) - 2) painter.setPen(QColor(0, 0, 0, 255)) painter.drawText( QRect(((base_img.width() / 2) + 21) - qr_size, base_img.height() - 107, base_img.width() - total_distance_h - border_thick - 93, base_img.height() - total_distance_h - border_thick), Qt.AlignLeft, self.versioned_seed.get_ui_string_version_plus_seed()) painter.drawText( QRect( 0, base_img.height() - 107, base_img.width() - total_distance_h - border_thick - 3 - qr_size, base_img.height() - total_distance_h - border_thick), Qt.AlignRight, self.versioned_seed.checksum) # draw qr code qr_qt = self.paintQR( self.versioned_seed.get_ui_string_version_plus_seed() + self.versioned_seed.checksum) target = QRectF(base_img.width() - 65 - qr_size, base_img.height() - 65 - qr_size, qr_size, qr_size) painter.drawImage(target, qr_qt) painter.setPen(QPen(Qt.black, 4)) painter.drawLine(base_img.width() - 65 - qr_size, base_img.height() - 65 - qr_size, base_img.width() - 65 - qr_size, (base_img.height() - ((total_distance_h))) - ((border_thick * 8)) - (border_thick / 2) - 4) painter.drawLine(base_img.width() - 65 - qr_size, base_img.height() - 65 - qr_size, base_img.width() - 65, base_img.height() - 65 - qr_size) painter.end() else: # calibration only painter.end() cal_img = QImage(self.f_size.width() + 100, self.f_size.height() + 100, QImage.Format_ARGB32) cal_img.fill(Qt.white) cal_painter = QPainter() cal_painter.begin(cal_img) cal_painter.drawImage(0, 0, base_img) #black lines in the middle of border top left only cal_painter.setPen(QPen(Qt.black, 1, Qt.DashDotDotLine)) cal_painter.drawLine(0, dist_v, base_img.width(), dist_v) cal_painter.drawLine(dist_h, 0, dist_h, base_img.height()) pen = QPen(Qt.black, 2, Qt.DashDotDotLine) cal_painter.setPen(pen) n = 15 cal_painter.setFont(QFont("DejaVu Sans Mono", 21, QFont.Bold)) for x in range(-n, n): #lines on bottom (vertical calibration) cal_painter.drawLine((((base_img.width()) / (n * 2)) * (x)) + (base_img.width() / 2) - 13, x + 2 + base_img.height() - (dist_v), (((base_img.width()) / (n * 2)) * (x)) + (base_img.width() / 2) + 13, x + 2 + base_img.height() - (dist_v)) num_pos = 9 if x > 9: num_pos = 17 if x < 0: num_pos = 20 if x < -9: num_pos = 27 cal_painter.drawText((((base_img.width()) / (n * 2)) * (x)) + (base_img.width() / 2) - num_pos, 50 + base_img.height() - (dist_v), str(x)) #lines on the right (horizontal calibrations) cal_painter.drawLine( x + 2 + (base_img.width() - (dist_h)), ((base_img.height() / (2 * n)) * (x)) + (base_img.height() / n) + (base_img.height() / 2) - 13, x + 2 + (base_img.width() - (dist_h)), ((base_img.height() / (2 * n)) * (x)) + (base_img.height() / n) + (base_img.height() / 2) + 13) cal_painter.drawText(30 + (base_img.width() - (dist_h)), ((base_img.height() / (2 * n)) * (x)) + (base_img.height() / 2) + 13, str(x)) cal_painter.end() base_img = cal_img return base_img
def timedvideo(self): self.timedWindow = TimedPopup(self.cam) self.timedWindow.setGeometry(QRect(500, 500, 200, 90)) self.timedWindow.show()
def __init__(self, parent): super(QWidget, self).__init__(parent) self.layout = QHBoxLayout(self) # Initialize tab screen self.tabs = QTabWidget() self.tabImage = QWidget() self.tabVideo = QWidget() self.tabWebcam = QWidget() self.tabs.resize(300, 200) # Add tabs self.tabs.addTab(self.tabImage, "Image") self.tabs.addTab(self.tabVideo, "Video") self.tabs.addTab(self.tabWebcam, "Webcam") # Create TAB IMAGE # Create textbox to get path of image self.imagePathI = QLineEdit(self.tabImage) self.imagePathI.setGeometry(QRect(20, 30, 450, 30)) # Create load Button to load image self.loadButtonI = QPushButton("Load", self.tabImage) self.loadButtonI.setGeometry(QRect(500, 30, 100, 30)) self.loadButtonI.clicked.connect(self.loadImage) # Create box to show image self.imageView = QGraphicsView(self.tabImage) self.imageView.setGeometry(QRect(20, 80, 450, 360)) # Create form to get parametes self.scaleLabelI = QLabel("Scale Factor:", self.tabImage) self.scaleLabelI.setGeometry(QRect(500, 200, 100, 30)) self.scaleSpinBoxI = QDoubleSpinBox(self.tabImage) self.scaleSpinBoxI.setGeometry(QRect(600, 200, 50, 30)) self.scaleSpinBoxI.setDecimals(1) self.scaleSpinBoxI.setMinimum(1.1) self.scaleSpinBoxI.setMaximum(2.0) self.scaleSpinBoxI.setSingleStep(0.1) self.MinNeighborLabelI = QLabel("Min Neighbor:", self.tabImage) self.MinNeighborLabelI.setGeometry(QRect(500, 300, 100, 30)) self.minNeighborSpinBoxI = QSpinBox(self.tabImage) self.minNeighborSpinBoxI.setGeometry(QRect(600, 300, 50, 30)) self.minNeighborSpinBoxI.setMinimum(1) self.minNeighborSpinBoxI.setMaximum(50) # Create button to Detect self.detectButtonI = QPushButton("Detect", self.tabImage) self.detectButtonI.setGeometry(QRect(550, 400, 100, 30)) self.detectButtonI.clicked.connect(self.detectOfImage) # END IMAGE TAB # Create VIDEO TAB # Create textbox to get path of video self.videoPath = QLineEdit(self.tabVideo) self.videoPath.setGeometry(QRect(20, 30, 450, 30)) # Create load Button to load video self.loadButtonV = QPushButton("Load", self.tabVideo) self.loadButtonV.setGeometry(QRect(500, 30, 100, 30)) self.loadButtonV.clicked.connect(self.loadVideo) # Create box to show video self.videoView = QGraphicsView(self.tabVideo) self.videoView.setGeometry(QRect(20, 80, 450, 360)) # Create form to get parametes self.scaleLabelV = QLabel("Scale Factor:", self.tabVideo) self.scaleLabelV.setGeometry(QRect(500, 100, 100, 30)) self.scaleSpinBoxV = QDoubleSpinBox(self.tabVideo) self.scaleSpinBoxV.setGeometry(QRect(600, 100, 50, 30)) self.scaleSpinBoxV.setDecimals(1) self.scaleSpinBoxV.setMinimum(1.1) self.scaleSpinBoxV.setMaximum(2.0) self.scaleSpinBoxV.setSingleStep(0.1) self.MinNeighborLabelV = QLabel("Min Neighbor:", self.tabVideo) self.MinNeighborLabelV.setGeometry(QRect(500, 200, 100, 30)) self.minNeighborSpinBoxV = QSpinBox(self.tabVideo) self.minNeighborSpinBoxV.setGeometry(QRect(600, 200, 50, 30)) self.minNeighborSpinBoxV.setMinimum(1) self.minNeighborSpinBoxV.setMaximum(50) # Create button to start or stop video self.startButton = QPushButton("Start", self.tabVideo) self.startButton.setGeometry(QRect(500, 300, 100, 30)) self.startButton.clicked.connect(self.startVideo) self.stopButton = QPushButton("Stop", self.tabVideo) self.stopButton.setGeometry(QRect(500, 400, 100, 30)) self.stopButton.clicked.connect(self.stopVideo) # END VIDEO TAB # Create WEBCAM TAB # Create box to show video self.camView = QGraphicsView(self.tabWebcam) self.camView.setGeometry(QRect(20, 30, 600, 350)) # Create form to get parametes self.scaleLabel = QLabel("Scale Factor:", self.tabWebcam) self.scaleLabel.setGeometry(QRect(30, 400, 100, 30)) self.scaleSpinBox = QDoubleSpinBox(self.tabWebcam) self.scaleSpinBox.setGeometry(QRect(100, 400, 50, 30)) self.scaleSpinBox.setDecimals(1) self.scaleSpinBox.setMinimum(1.1) self.scaleSpinBox.setMaximum(2.0) self.scaleSpinBox.setSingleStep(0.1) self.MinNeighborLabel = QLabel("Min Neighbor:", self.tabWebcam) self.MinNeighborLabel.setGeometry(QRect(200, 400, 100, 30)) self.minNeighborSpinBox = QSpinBox(self.tabWebcam) self.minNeighborSpinBox.setGeometry(QRect(280, 400, 50, 30)) self.minNeighborSpinBox.setMinimum(1) self.minNeighborSpinBox.setMaximum(50) # Create button to turn on or turn off webcam self.turnOnButton = QPushButton("On", self.tabWebcam) self.turnOnButton.setGeometry(QRect(450, 400, 80, 30)) self.turnOnButton.clicked.connect(self.turnOn) self.turnOffButton = QPushButton("Off", self.tabWebcam) self.turnOffButton.setGeometry(QRect(550, 400, 80, 30)) self.turnOffButton.clicked.connect(self.turnOff) # END WEBCAM TAB # Add tabs to widget self.layout.addWidget(self.tabs) self.setLayout(self.layout)
def test_simple(self, stubs, js_rect): geometry = QRect(5, 5, 4, 4) frame = stubs.FakeWebFrame(QRect(0, 0, 100, 100)) elem = get_webelem(geometry, frame, js_rect_return=js_rect) assert elem.rect_on_view() == QRect(5, 5, 4, 4)
def setupUi(self): self.centralwidget = QWidget(self) with open(resource_path('style.css'), 'r') as file: self.centralwidget.setStyleSheet(file.read()) self.appswidget = QWidget(self.centralwidget) self.appswidget.setGeometry(50, 0, 490, 470) self.appswidget.setProperty('class', 'appswidget') self.sidebar = QFrame(self) self.sidebar.setFrameShape(QFrame.StyledPanel) self.sidebar.setGeometry(0, 0, 50, 470) self.sidebar.setProperty('class', 'sidebar') self.refresh_btn = QPushButton(self.sidebar) self.refresh_btn.setGeometry(QRect(0, 0, 51, 51)) self.refresh_btn.setProperty('class', 'sidebar_btns') self.refresh_btn.setIcon(QIcon(':/icon/refresh_icon.png')) self.refresh_btn.setIconSize(QSize(24, 24)) self.refresh_bind = QShortcut(QKeySequence('Ctrl+R'), self) self.store_btn = QPushButton(self.sidebar) self.store_btn.setGeometry(QRect(0, 51, 51, 51)) self.store_btn.setProperty('class', 'sidebar_btns') self.store_btn.setIcon(QIcon(':/icon/store_icon.png')) self.store_btn.setIconSize(QSize(24, 24)) self.store_bind = QShortcut(QKeySequence('Ctrl+S'), self) self.homepage_btn = QPushButton(self.sidebar) self.homepage_btn.setGeometry(QRect(0, 102, 51, 51)) self.homepage_btn.setProperty('class', 'sidebar_btns') self.homepage_btn.setIcon(QIcon(':/icon/github_icon.png')) self.homepage_btn.setIconSize(QSize(24, 24)) self.homepage_bind = QShortcut(QKeySequence('Ctrl+G'), self) self.about_btn = QPushButton(self.sidebar) self.about_btn.setGeometry(QRect(0, 153, 51, 51)) self.about_btn.setProperty('class', 'sidebar_btns') self.about_btn.setIcon(QIcon(':/icon/about_icon.png')) self.about_btn.setIconSize(QSize(24, 24)) self.about_bind = QShortcut(QKeySequence('Ctrl+A'), self) self.quit_btn = QPushButton(self.sidebar) self.quit_btn.setGeometry(QRect(0, 420, 51, 51)) self.quit_btn.setProperty('class', 'sidebar_btns_quit') self.quit_btn.setIcon(QIcon(':/icon/quit_icon.png')) self.quit_btn.setIconSize(QSize(24, 24)) self.quit_bind = QShortcut(QKeySequence('Ctrl+Q'), self) self.font = QFont() self.font.setPointSize(8) self.font.setStyleStrategy(QFont.PreferAntialias) self.label_refresh = QLabel(self.appswidget) self.label_refresh.setFont(self.font) self.label_refresh.setGeometry(QRect(20, 10, 441, 15)) self.label_info = QLabel(self.appswidget) self.label_info.setFont(self.font) self.label_info.setGeometry(QRect(20, 15, 441, 30)) self.progressbar = QProgressBar(self.appswidget) self.progressbar.setGeometry(QRect(20, 35, 441, 20)) self.verticalLayoutWidget = QWidget(self.appswidget) self.verticalLayoutWidget.setGeometry(QRect(20, 55, 150, 311)) self.verticalLayout = QVBoxLayout(self.verticalLayoutWidget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.checkBox = QCheckBox(self.verticalLayoutWidget) self.checkBox_2 = QCheckBox(self.verticalLayoutWidget) self.checkBox_3 = QCheckBox(self.verticalLayoutWidget) self.checkBox_4 = QCheckBox(self.verticalLayoutWidget) self.checkBox_5 = QCheckBox(self.verticalLayoutWidget) self.checkBox_6 = QCheckBox(self.verticalLayoutWidget) self.checkBox_7 = QCheckBox(self.verticalLayoutWidget) self.checkBox_8 = QCheckBox(self.verticalLayoutWidget) self.checkBox_9 = QCheckBox(self.verticalLayoutWidget) self.checkBox_10 = QCheckBox(self.verticalLayoutWidget) self.checkBox_11 = QCheckBox(self.verticalLayoutWidget) checkbox_column_1 = (self.checkBox, self.checkBox_2, self.checkBox_3, self.checkBox_4, self.checkBox_5, self.checkBox_6, self.checkBox_7, self.checkBox_8, self.checkBox_9, self.checkBox_10, self.checkBox_11 ) for checkbox in checkbox_column_1: self.verticalLayout.addWidget(checkbox) self.verticalLayoutWidget_2 = QWidget(self.appswidget) self.verticalLayoutWidget_2.setGeometry(QRect(175, 55, 150, 311)) self.verticalLayout_2 = QVBoxLayout(self.verticalLayoutWidget_2) self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) self.checkBox_12 = QCheckBox(self.verticalLayoutWidget_2) self.checkBox_13 = QCheckBox(self.verticalLayoutWidget_2) self.checkBox_14 = QCheckBox(self.verticalLayoutWidget_2) self.checkBox_15 = QCheckBox(self.verticalLayoutWidget_2) self.checkBox_16 = QCheckBox(self.verticalLayoutWidget_2) self.checkBox_17 = QCheckBox(self.verticalLayoutWidget_2) self.checkBox_18 = QCheckBox(self.verticalLayoutWidget_2) self.checkBox_19 = QCheckBox(self.verticalLayoutWidget_2) self.checkBox_20 = QCheckBox(self.verticalLayoutWidget_2) self.checkBox_21 = QCheckBox(self.verticalLayoutWidget_2) self.checkBox_22 = QCheckBox(self.verticalLayoutWidget_2) checkbox_column_2 = (self.checkBox_12, self.checkBox_13, self.checkBox_14, self.checkBox_15, self.checkBox_16, self.checkBox_17, self.checkBox_18, self.checkBox_19, self.checkBox_20, self.checkBox_21, self.checkBox_22 ) for checkbox in checkbox_column_2: self.verticalLayout_2.addWidget(checkbox) self.verticalLayoutWidget_3 = QWidget(self.appswidget) self.verticalLayoutWidget_3.setGeometry(QRect(330, 55, 150, 311)) self.verticalLayout_3 = QVBoxLayout(self.verticalLayoutWidget_3) self.verticalLayout_3.setContentsMargins(0, 0, 0, 0) self.checkBox_23 = QCheckBox(self.verticalLayoutWidget_3) self.checkBox_24 = QCheckBox(self.verticalLayoutWidget_3) self.checkBox_25 = QCheckBox(self.verticalLayoutWidget_3) self.checkBox_26 = QCheckBox(self.verticalLayoutWidget_3) self.checkBox_27 = QCheckBox(self.verticalLayoutWidget_3) self.checkBox_28 = QCheckBox(self.verticalLayoutWidget_3) self.checkBox_29 = QCheckBox(self.verticalLayoutWidget_3) self.checkBox_30 = QCheckBox(self.verticalLayoutWidget_3) self.checkBox_31 = QCheckBox(self.verticalLayoutWidget_3) self.checkBox_32 = QCheckBox(self.verticalLayoutWidget_3) self.checkBox_33 = QCheckBox(self.verticalLayoutWidget_3) checkbox_column_3 = (self.checkBox_23, self.checkBox_24, self.checkBox_25, self.checkBox_26, self.checkBox_27, self.checkBox_28, self.checkBox_29, self.checkBox_30, self.checkBox_31, self.checkBox_32, self.checkBox_33 ) for checkbox in checkbox_column_3: self.verticalLayout_3.addWidget(checkbox) self.label_note = QLabel(self.appswidget) self.label_note.setFont(self.font) self.label_note.setGeometry(QRect(20, 370, 350, 16)) self.horizontalLayoutWidget_3 = QWidget(self.appswidget) self.horizontalLayoutWidget_3.setGeometry(QRect(20, 390, 350, 16)) self.horizontalLayout_3 = QHBoxLayout(self.horizontalLayoutWidget_3) self.horizontalLayout_3.setContentsMargins(0, 0, 0, 0) self.label_space = QLabel(self.appswidget) self.label_space.setFont(self.font) self.horizontalLayout_3.addWidget(self.label_space) self.label_size = QLabel(self.appswidget) self.label_size.setFont(self.font) self.horizontalLayout_3.addWidget(self.label_size) self.horizontalLayoutWidget_2 = QWidget(self.appswidget) self.horizontalLayoutWidget_2.setGeometry(QRect(20, 420, 220, 31)) self.horizontalLayout_2 = QHBoxLayout(self.horizontalLayoutWidget_2) self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0) self.button_select_all = QPushButton(self.horizontalLayoutWidget_2) self.button_select_all.setIcon(QIcon(':/icon/check_icon.png')) self.button_select_all.setIconSize(QSize(18, 18)) self.button_select_all.setLayoutDirection(Qt.RightToLeft) self.horizontalLayout_2.addWidget(self.button_select_all) self.button_select_all.setMinimumSize(100, 30) self.button_select_all.setProperty('class', 'Aqua') self.button_deselect_all = QPushButton(self.horizontalLayoutWidget_2) self.button_deselect_all.setIcon(QIcon(':/icon/cancel_icon.png')) self.button_deselect_all.setIconSize(QSize(18, 18)) self.button_deselect_all.setLayoutDirection(Qt.RightToLeft) self.horizontalLayout_2.addWidget(self.button_deselect_all) self.button_deselect_all.setMinimumSize(100, 30) self.button_deselect_all.setProperty('class', 'Aqua') self.horizontalLayoutWidget = QWidget(self.appswidget) self.horizontalLayoutWidget.setGeometry(QRect(354, 420, 107, 31)) self.horizontalLayout = QHBoxLayout(self.horizontalLayoutWidget) self.horizontalLayout.setContentsMargins(0, 0, 0, 0) self.button_uninstall = QPushButton(self.horizontalLayoutWidget) self.button_uninstall.setIcon(QIcon(':/icon/trash_icon.png')) self.button_uninstall.setIconSize(QSize(18, 18)) self.button_uninstall.setLayoutDirection(Qt.RightToLeft) self.horizontalLayout.addWidget(self.button_uninstall) self.button_uninstall.setMinimumSize(100, 30) self.button_uninstall.setProperty('class', 'Grapefruit') with open(resource_path('style.css'), 'r') as file: widgets = (self.sidebar, self.refresh_btn, self.homepage_btn, self.about_btn, self.quit_btn, self.progressbar, self.button_select_all, self.button_deselect_all, self.button_uninstall ) for widget in widgets: widget.setStyleSheet(file.read()) self.setCentralWidget(self.centralwidget) self.retranslateUi() QMetaObject.connectSlotsByName(self)
def test_css_attributes(self, frame, style, visible): elem = get_webelem(QRect(0, 0, 10, 10), frame, style=style) assert elem._is_visible(frame) == visible
def test_scrolled(self, stubs, js_rect): geometry = QRect(20, 20, 4, 4) frame = stubs.FakeWebFrame(QRect(0, 0, 100, 100), scroll=QPoint(10, 10)) elem = get_webelem(geometry, frame, js_rect_return=js_rect) assert elem.rect_on_view() == QRect(20 - 10, 20 - 10, 4, 4)
def setupUi(self, MainWindow): resolution = QDesktopWidget().screenGeometry(self) # MainWindow.setGeometry(QRect(0,0,0,0)) MainWindow.setFixedSize(resolution.size().width()*0.99, resolution.size().height()*0.90)#1200 800 # self.setWindowState(Qt.WindowMaximized) print("resol : ", MainWindow.size()) #메인 화면 색상py self.setStyleSheet("color: black;" "background-color: white;") font = QFont() font.setFamily("NanumGothic") MainWindow.setFont(font) self.centralwidget = QWidget(MainWindow) self.label = QLabel(self.centralwidget) self.label.setGeometry(QRect(20, 20, 130, 35)) font = QFont() font.setFamily("NanumGothic") font.setPointSize(18) font.setBold(True) font.setWeight(75) self.label.setFont(font) self.button_add = QPushButton(self.centralwidget) self.button_add.setGeometry(QRect(MainWindow.size().width()*0.05, MainWindow.size().height() - 80, 131, 34)) #버튼 스타일 변경 self.button_add.setStyleSheet(staticValues.blueButtonStyleSheet) self.button_add.setFont(staticValues.buttonFont) self.button_modi = QPushButton(self.centralwidget) self.button_modi.setGeometry(QRect(MainWindow.size().width()*0.20, MainWindow.size().height() - 80, 131, 34)) self.button_modi.setStyleSheet(staticValues.blueButtonStyleSheet) self.button_modi.setFont(staticValues.buttonFont) self.button_del = QPushButton(self.centralwidget) self.button_del.setGeometry(QRect(MainWindow.size().width()*0.35, MainWindow.size().height() - 80, 131, 34)) self.button_del.setStyleSheet(staticValues.redButtonStyleSheet) self.button_del.setFont(staticValues.buttonFont) self.button_upload = QPushButton(self.centralwidget) self.button_upload.setGeometry(QRect(MainWindow.size().width()*0.7, MainWindow.size().height() - 80, 131, 34)) self.button_upload.setStyleSheet(staticValues.grayButtonStyleSheet) self.button_upload.setFont(staticValues.buttonFont) self.tabWidget = QTabWidget(self.centralwidget) self.tabWidget.setGeometry(QRect(10, 70, MainWindow.size().width()-15, MainWindow.size().height() - 180)) self.tab = QWidget() self.tab.layout = QVBoxLayout() self.tabWidget.addTab(self.tab, "회원 목록") self.tableWidget = QTableWidget(self.tab) self.tableWidget.setGeometry(QRect(0, 0, self.tabWidget.size().width()-5, self.tabWidget.size().height()-25)) self.tableWidget.setColumnCount(13) self.tableWidget.setRowCount(0) self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows) self.tableWidget.setHorizontalHeaderLabels(["회원 ID", "단톡방", "코인명", "구매", "입금", "판매", "출근" , "보유잔량", "총구매금액", "총판매금액", "수익", "평단가", "지갑주소"]) self.tab2 = QWidget() self.tab2.layout = QVBoxLayout() self.tabWidget.addTab(self.tab2, "중복 회원") self.label_updateDate = QLabel(self.tab2) self.label_updateDate.setGeometry(QRect(0, 0, 250, 35)) self.tableWidget2 = QTableWidget(self.tab2) self.tableWidget2.setGeometry(QRect(0, 30, self.tabWidget.size().width()-5, self.tabWidget.size().height()-55)) self.tableWidget2.setColumnCount(3) self.tableWidget2.setRowCount(0) self.tableWidget2.setSelectionBehavior(QAbstractItemView.SelectRows) self.tableWidget.setHorizontalHeaderLabels(["회원 ID", "현재 단톡방", "중복 단톡방"]) self.edit_search = QLineEdit(self.centralwidget) self.edit_search.setGeometry(QRect(MainWindow.size().width()-280, 35, 200, 30)) self.edit_search.setStyleSheet(staticValues.solidStyleSheet) self.button_search = QPushButton(self.centralwidget) self.button_search.setGeometry(QRect(MainWindow.size().width()-80, 35, 70, 30)) self.button_search.setStyleSheet(staticValues.grayButtonStyleSheet) self.button_search.setFont(staticValues.buttonFont) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(0) QMetaObject.connectSlotsByName(MainWindow)
def drawWidget(self, qp): # color settings: cWhite = QColor(255, 255, 255) cBlack = QColor(0, 0, 0) cDarkGreen = QColor(119, 177, 80) cOrangeYellow = QColor(255, 208, 98) cLightGrey = QColor(155, 155, 155) cBackGroundNorm = cWhite # Normal Widget Background cBackGroundOutOfRange = QColor( 255, 230, 230) # Widget Background if parameter is at bound cAxis = QColor(215, 215, 215) # Axis and Scale bars cBoundInterval = cBlack # axis interval bewtween bounds cPrefValueMarker = QColor(31, 78, 121) # preferred Value Marker cPrefValueRange = QColor(95, 157, 214) # prior information range cCurrentValueMarker = QColor(216, 108, 0) cPosteriorValueRange = cOrangeYellow cValueMarkerOutOfRange = QColor(255, 38, 0) cDevInterval = QColor(255, 50, 50) # shape settings yAxisWidth = 1 yDrawAreaHeight = 15 xHorizontalMargin = 10 xMarkerCurrentWidth = 1 yMarkerCurrentHeight = 7 yPosteriorHeight = 7 xMarkerPrefWidth = 1 yMarkerPrefHeight = 3 yPriorHeight = 3 yBracketHeight = 3 yDevBarHeight = 5 # important locations: actualWidgetSize = self.size() w = actualWidgetSize.width() h = actualWidgetSize.height() xDrawAreaWidth = w - 2 * xHorizontalMargin xLeft = xHorizontalMargin xRight = actualWidgetSize.width() - xHorizontalMargin xCenter = int((xLeft + xRight) / 2) yCenter = int(h / 2) yHigh = yCenter - (yDrawAreaHeight - 1) / 2 yLow = yCenter + (yDrawAreaHeight - 1) / 2 # some pointers for better readability: parval = self.parval prefval = self.prefval axmin = self.minAxis axmax = self.maxAxis parlbnd = self.parlbnd parubnd = self.parubnd prior = self.priorStdev posterior = self.posteriorStdev # check if value is out of range if self.parval <= self.parlbnd or self.parval >= self.parubnd: cBackground = cBackGroundOutOfRange else: cBackground = cBackGroundNorm # paint background: rectBackground = QRect(0, 0, w - 1, h - 1) # left, top, height, width qp.setPen(cWhite) qp.setBrush(cBackground) qp.drawRect(rectBackground) # paint posterior parameter range center = xHorizontalMargin + xDrawAreaWidth * (parval - axmin) / (axmax - axmin) width = int(posterior * xDrawAreaWidth / (axmax - axmin) * 6) left = int(center - width / 2) top = yCenter - yPosteriorHeight height = yPosteriorHeight rectPosteriorRange = QRect(left, top, width, height) gradient = QLinearGradient(QPointF(left, top), QPointF(left + width / 2, top + height)) gradient.setSpread(1) gradient.setStops([(0, cBackground), (0.66, cPosteriorValueRange), (1, cPosteriorValueRange)]) qp.setBrush(gradient) qp.setPen(Qt.NoPen) if self.PostCalRangeVisible: qp.drawRect(rectPosteriorRange) # draw scale scalebars = [self.scaleBase] while scalebars[0] > axmin: scalebars.insert(0, scalebars[0] - self.scaleInterval) while scalebars[-1] < axmax: scalebars.append(scalebars[-1] + self.scaleInterval) for sb in scalebars: sbx = xHorizontalMargin + (xDrawAreaWidth * (sb - axmin) / (axmax - axmin)) LineSb = QLine(sbx, yCenter - 1, sbx, yCenter + 2) qp.setPen(cAxis) qp.drawLine(LineSb) # paint current parameter marker xCurrentMCenter = xHorizontalMargin + xDrawAreaWidth * ( parval - axmin) / (axmax - axmin) left = xCurrentMCenter - (xMarkerCurrentWidth - 1) / 2 rectCurrentParvalue = QRect(left, yCenter - yMarkerCurrentHeight, xMarkerCurrentWidth, yMarkerCurrentHeight) if self.parval <= self.parlbnd or self.parval >= self.parubnd: qp.setBrush(cValueMarkerOutOfRange) qp.setPen(cValueMarkerOutOfRange) else: qp.setBrush(cCurrentValueMarker) qp.setPen(cCurrentValueMarker) qp.drawRect(rectCurrentParvalue) # paint prior parameter range center = xHorizontalMargin + xDrawAreaWidth * (prefval - axmin) / (axmax - axmin) width = int(prior * xDrawAreaWidth / (axmax - axmin) * 6) left = int(center - width / 2) top = int(h / 2) + 1 height = yPriorHeight rectPriorRange = QRect(left, yCenter + 1, width, yPriorHeight) gradient = QLinearGradient(QPointF(left, top), QPointF(left + width / 2, top + height)) gradient.setSpread(1) gradient.setStops([(0, cBackground), (0.66, cPrefValueRange), (1, cPrefValueRange)]) qp.setBrush(gradient) qp.setPen(Qt.NoPen) if self.PreCalRangeVisible: qp.drawRect(rectPriorRange) # paint preferred parameter marker xPrefMCenter = xHorizontalMargin + xDrawAreaWidth * ( prefval - axmin) / (axmax - axmin) left = xPrefMCenter - (xMarkerPrefWidth - 1) / 2 rectPrefParvalue = QRect(left, yCenter + 1, xMarkerPrefWidth, yMarkerPrefHeight) qp.setBrush(cPrefValueMarker) qp.setPen(cPrefValueMarker) qp.drawRect(rectPrefParvalue) # draw parameter axis lineAxis = QLine(xLeft, yCenter, xRight, yCenter) # qp.setPen(Qt.DotLine) qp.setPen(cAxis) qp.drawLine(lineAxis) # draw bound bracket xUbound = xHorizontalMargin + (xDrawAreaWidth * (parubnd - axmin) / (axmax - axmin)) xLbound = xHorizontalMargin + (xDrawAreaWidth * (parlbnd - axmin) / (axmax - axmin)) LineUbound = QLine(xUbound, yCenter - yBracketHeight, xUbound, yCenter) LineLbound = QLine(xLbound, yCenter, xLbound, yCenter - yBracketHeight) LineBoundInterval = QLine(xLbound, yCenter, xUbound, yCenter) qp.setPen(cBoundInterval) if self.BoundBracketVisible: qp.drawLine(LineUbound) qp.drawLine(LineBoundInterval) qp.drawLine(LineLbound) # draw deviation bracket """ LineCbound = QLine(xCurrentMCenter, yCenter - yBracketHeight, xCurrentMCenter, yCenter) LinePbound = QLine(xPrefMCenter, yCenter, xPrefMCenter, yCenter + yBracketHeight) LineDevInterval = QLine(xCurrentMCenter, yCenter, xPrefMCenter, yCenter) qp.setPen(cDevInterval) qp.drawLine(LineCbound) qp.drawLine(LinePbound) qp.drawLine(LineDevInterval) """ # draw deviation bar center = xHorizontalMargin + xDrawAreaWidth * (prefval - axmin) / (axmax - axmin) width = xUbound - xLbound left = xLbound top = yCenter - yDevBarHeight / 2 height = yDevBarHeight rect1stdev = QRect(center, top, xCurrentMCenter - xPrefMCenter, height) gradient = QLinearGradient(QPointF(left, top), QPointF(left + width / 2, top + height)) gradient.setSpread(1) gradient.setStops([(1.00, cDarkGreen), (0.67, cDarkGreen), (0.65, cOrangeYellow), (0.34, cOrangeYellow), (0.32, cValueMarkerOutOfRange), (0.00, cValueMarkerOutOfRange)]) qp.setPen(Qt.NoPen) qp.setBrush(gradient) if self.DevBarVisible: qp.drawRect(rect1stdev)
def __init__(self, parent=None): super(IconButton, self).__init__(parent=parent) # rect property contains the active zone for the button self.rect = QRect() self.icon_rect = QRect() self.icon_mode = QIcon.Normal
def drawWidget(self, qp): # color settings: cWhite = QColor(255, 255, 255) cBlack = QColor(0, 0, 0) cBackGroundNorm = cWhite cBackGroundOutOfRange = QColor(255, 230, 230) cAxis = QColor(155, 155, 155) cBoundInterval = cBlack cPrefValueMarker = QColor(31, 78, 121) cPrefValueRange = QColor(95, 157, 214) cCurrentValueMarker = QColor(56, 87, 35) cPosteriorValueRange = QColor(119, 177, 80) cValueMarkerOutOfRange = QColor(255, 38, 0) # shape settings axisWidth = 1 yDrawAreaHeight = 15 xHorizontalMargin = 10 yMarkerCurrentHeight = 7 xMarkerCurrentWidth = 3 yMarkerPrefHeight = 4 xMarkerPrefWidth = 3 yPriorHeight = 3 yPosteriorHeight = 4 # important locations: actualWidgetSize = self.size() w = actualWidgetSize.width() h = actualWidgetSize.height() xDrawAreaWidth = w - 2 * xHorizontalMargin xLeft = xHorizontalMargin xRight = actualWidgetSize.width() - xHorizontalMargin xCenter = int((xLeft + xRight) / 2) yCenter = int(h / 2) yHigh = yCenter - (yDrawAreaHeight - 1) / 2 yLow = yCenter + (yDrawAreaHeight - 1) / 2 # some pointers for better readability: parval = self.parval prefval = self.prefval axmin = self.minAxis axmax = self.maxAxis parlbnd = self.parlbnd parubnd = self.parubnd prior = self.priorStdev posterior = self.posteriorStdev # paint background: rectBackground = QRect(0, 0, w - 1, h - 1) # left, top, height, width qp.setPen(Qt.NoPen) qp.setBrush(cBackGroundNorm) qp.drawRect(rectBackground) # draw scale scalebars = [self.scaleBase] while scalebars[0] > axmin: scalebars.insert(0, scalebars[0] - self.scaleInterval) while scalebars[-1] < axmax: scalebars.append(scalebars[-1] + self.scaleInterval) for sb in scalebars: scaletext = str(sb) + " m/d" if self.logTransform: scaletext = "10^" + scaletext sbx = xHorizontalMargin + (xDrawAreaWidth * (sb - axmin) / (axmax - axmin)) # LineSb = QLine(sbx, yCenter - 1, sbx, yCenter + 2) qp.setPen(cBlack) # qp.drawLine(LineSb) font = QFont('Serif', 7, QFont.Light) qp.setFont(font) metrics = qp.fontMetrics() fw = metrics.width(scaletext) fh = metrics.height() qp.drawText(sbx - fw / 2, yCenter + fh / 2, scaletext)
def __init__(self, mainR): QMainWindow.__init__(self) _translate = QCoreApplication.translate self.mainW = mainR self.setMinimumSize(QSize(360,240)) self.setObjectName("SettingsWindow") self.centralwidget = QWidget(self) self.centralwidget.setObjectName("centralwidget") self.gridLayout = QGridLayout(self.centralwidget) self.gridLayout.setObjectName("gridLayout") self.btn_apply = QPushButton(self.centralwidget) self.btn_apply.setObjectName("btn_apply") self.btn_apply.clicked.connect(self.apply_settings) self.gridLayout.addWidget(self.btn_apply, 3, 0, 1, 1) self.tabWidget = QTabWidget(self.centralwidget) self.tabWidget.setObjectName("tabWidget") ###--- Location ---### self.tab_location = QWidget() self.tab_location.setObjectName("tab_location") self.layout_location = QGridLayout(self.tab_location) self.layout_location.setObjectName("layout_location") self.formLayout = QFormLayout() self.formLayout.setObjectName("formLayout") ## Saved coordinates self.coordinates = settings.load_coordinates() lbl_country = QLabel(self.tab_location) lbl_country.setObjectName("lbl_country") self.combo_country = QComboBox(self.tab_location) self.combo_country.setObjectName("combo_country") self.combo_country.addItems(self.coordinates.keys()) lbl_prov = QLabel(self.tab_location) lbl_prov.setObjectName("lbl_prov") self.combo_prov = QComboBox(self.tab_location) self.combo_prov.setObjectName("combo_prov") lbl_city = QLabel(self.tab_location) lbl_city.setObjectName("lbl_city") self.combo_city = QComboBox(self.tab_location) self.combo_city.setObjectName("combo_city") #self.combo_country.setCurrentText('') #lambda x: self.combo_prov.addItems(coordinates[x]) #lambda x: combo_city.addItems(coordinates[x]) self.formLayout.setWidget(1, QFormLayout.LabelRole, lbl_country) self.formLayout.setWidget(1, QFormLayout.FieldRole, self.combo_country) self.formLayout.setWidget(2, QFormLayout.LabelRole, lbl_prov) self.formLayout.setWidget(2, QFormLayout.FieldRole, self.combo_prov) self.formLayout.setWidget(3, QFormLayout.LabelRole, lbl_city) self.formLayout.setWidget(3, QFormLayout.FieldRole, self.combo_city) ## Custom # Latitude self.lbl_lat = QLabel(self.tab_location) self.lbl_lat.setObjectName("lbl_lat") self.txt_lat = QLineEdit(self.tab_location) self.txt_lat.setObjectName("txt_lat") self.txt_lat.setText(str(settings.location['lat'])) self.txt_lat.setValidator( QDoubleValidator(-90.0, 90.0, 5)) self.formLayout.setWidget(4, QFormLayout.FieldRole, self.txt_lat) self.formLayout.setWidget(4, QFormLayout.LabelRole, self.lbl_lat) # Longitude self.lbl_lon = QLabel(self.tab_location) self.lbl_lon.setObjectName("lbl_lon") self.txt_lon = QLineEdit(self.tab_location) self.txt_lon.setObjectName("txt_lon") self.txt_lon.setValidator( QDoubleValidator(-180.0, 180.0, 5)) self.txt_lon.setText(str(settings.location['lon'])) self.formLayout.setWidget(5, QFormLayout.LabelRole, self.lbl_lon) self.formLayout.setWidget(5, QFormLayout.FieldRole, self.txt_lon) # Timezone self.lbl_tz = QLabel(self.tab_location) self.lbl_tz.setObjectName("lbl_tz") self.txt_tz = QLineEdit(self.tab_location) self.txt_tz.setObjectName("txt_tz") self.txt_tz.setValidator( QDoubleValidator(-12, 14, 2)) self.txt_tz.setText(str(settings.location['tz'])) self.formLayout.setWidget(6, QFormLayout.LabelRole, self.lbl_tz) self.formLayout.setWidget(6, QFormLayout.FieldRole, self.txt_tz) # Calculation method self.lbl_calc = QLabel(self.tab_location) self.lbl_calc.setObjectName("lbl_calc") self.combo_calc = QComboBox(self.tab_location) self.combo_calc.setObjectName("combo_calc") calcCodes = prayTimes.methods for code in calcCodes: self.combo_calc.addItem(code) if (settings.location['calcCode'] != ''): #self.combo_calc.setCurrentText(settings.calcCode) self.combo_calc.setCurrentIndex( self.combo_calc.findText(settings.location['calcCode'])) self.formLayout.setWidget(7, QFormLayout.LabelRole, self.lbl_calc) self.formLayout.setWidget(7, QFormLayout.FieldRole, self.combo_calc) self.layout_location.addLayout(self.formLayout, 0, 0, 1, 1) self.tabWidget.addTab(self.tab_location, "") # Extra functions self.combo_country.currentTextChanged.connect(self.setProvText) self.combo_prov.currentTextChanged.connect(self.setCityText) self.combo_city.currentTextChanged.connect(self.setCoordinates) self.combo_country.setCurrentIndex( self.combo_country.findText(settings.location['country'])) self.combo_prov.setCurrentIndex( self.combo_prov.findText(settings.location['province'])) self.combo_city.setCurrentIndex( self.combo_city.findText(settings.location['city'])) self.setWindowTitle(_translate("SettingsWindow", "Settings")) lbl_country.setText(_translate("SettingsWindow", "Country")) lbl_prov.setText(_translate("SettingsWindow", "Province")) lbl_city.setText(_translate("SettingsWindow", "City")) self.lbl_lat.setText(_translate("SettingsWindow", "Latitude")) self.lbl_lon.setText(_translate("SettingsWindow", "Longitude")) self.lbl_tz.setText(_translate("SettingsWindow", "Timezone")) self.lbl_calc.setText(_translate("SettingsWindow", "Calculation Method")) self.btn_apply.setText(_translate("SettingsWindow", "Apply")) ###--- Reminders ---### self.tab_reminders = QWidget() self.tab_reminders.setObjectName("tab_reminders") self.layout_reminders = QGridLayout(self.tab_reminders) self.layout_reminders.setObjectName("layout_reminders") self.scrollArea = QScrollArea(self.tab_reminders) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName("scrollArea") self.scrollAreaWidgetContents = QWidget() self.scrollAreaWidgetContents.setGeometry(QRect(0, 0, 304, 598)) self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents") self.verticalLayout = QVBoxLayout(self.scrollAreaWidgetContents) self.verticalLayout.setObjectName("verticalLayout") ##-- Athan group--## self.group_athan = QGroupBox(self.scrollAreaWidgetContents) self.group_athan.setObjectName("group_athan") self.group_athan_layout = QGridLayout(self.group_athan) self.group_athan_layout.setObjectName("group_athan_layout") self.check_athan = {} y = 1 x = 0 for name in ['Fajr', 'Dhuhr', 'Asr', 'Maghrib', 'Isha']: self.check_athan[name.lower()] = QCheckBox(self.group_athan) self.check_athan[name.lower()].setObjectName("check_athan_" + name.lower()) self.check_athan[name.lower()].setText(_translate("SettingsWindow", name)) self.check_athan[name.lower()].setChecked( settings.reminder_athan[name.lower() + '_enabled'] == '1') self.group_athan_layout.addWidget(self.check_athan[name.lower()], y, x, 1, 1) if name == 'Asr': y = 1 x = 1 else: y += 1 # self.desc_athan_method = QLabel(self.group_athan) # self.desc_athan_method.setObjectName("desc_athan_method") self.desc_athan = QLabel(self.group_athan) self.desc_athan.setObjectName("desc_athan") # self.check_athan_dialog = QCheckBox(self.group_athan) # self.check_athan_dialog.setObjectName("check_athan_dialog") # self.check_athan_dialog.setChecked( # settings.reminder_athan['dialog_enabled'] == '1') # self.check_athan_notification = QCheckBox(self.group_athan) # self.check_athan_notification.setObjectName("check_athan_notification") # self.check_athan_notification.setChecked( # settings.reminder_athan['notification_enabled'] == '1') # self.group_athan_layout.addWidget(self.desc_athan_method, 4, 0, 1, 2) self.group_athan_layout.addWidget(self.desc_athan, 0, 0, 1, 2) # self.group_athan_layout.addWidget(self.check_athan_dialog, 5, 0, 1, 2) # self.group_athan_layout.addWidget(self.check_athan_notification, 6, 0, 1, 2) self.verticalLayout.addWidget(self.group_athan) ##-- Iqomah --## self.group_iqomah = QGroupBox(self.scrollAreaWidgetContents) self.group_iqomah.setFlat(False) self.group_iqomah.setCheckable(False) self.group_iqomah.setObjectName("group_iqomah") self.group_iqomah_layout = QGridLayout(self.group_iqomah) self.group_iqomah_layout.setObjectName("group_iqomah_layout") valid_iqomah = QIntValidator(1, 60) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) self.check_iqomah = {} self.text_iqomah = {} y = 2 for name in ['Fajr', 'Dhuhr', 'Asr', 'Maghrib', 'Isha']: self.check_iqomah[name.lower()] = QCheckBox(self.group_iqomah) self.check_iqomah[name.lower()].setObjectName("check_iqomah_" + name.lower()) self.check_iqomah[name.lower()].setText(_translate("SettingsWindow", name)) self.check_iqomah[name.lower()].setChecked( settings.reminder_iqomah[name.lower() + '_enabled'] == '1') self.text_iqomah[name.lower()] = QLineEdit(self.group_iqomah) self.text_iqomah[name.lower()].setSizePolicy(sizePolicy) self.text_iqomah[name.lower()].setBaseSize(QSize(0, 0)) self.text_iqomah[name.lower()].setReadOnly(False) self.text_iqomah[name.lower()].setObjectName("txt_iqomah_" + name.lower()) self.text_iqomah[name.lower()].setValidator(valid_iqomah) self.text_iqomah[name.lower()].setText( settings.reminder_iqomah[name.lower() + '_time']) self.text_iqomah[name.lower()].setDisabled(not self.check_iqomah[name.lower()].isChecked()) self.check_iqomah[name.lower()].toggled.connect( lambda state, n=name.lower(): self.text_iqomah[n].setDisabled(not state)) self.group_iqomah_layout.addWidget(self.check_iqomah[name.lower()], y, 0, 1, 1) self.group_iqomah_layout.addWidget(self.text_iqomah[name.lower()], y, 1, 1, 1) y += 1 # self.check_iqomah_notification = QCheckBox(self.group_iqomah) # self.check_iqomah_notification.setObjectName("check_iqomah_notification") # self.check_iqomah_notification.setChecked( # settings.reminder_iqomah['notification_enabled'] == '1') self.desc_iqomah = QLabel(self.group_iqomah) self.desc_iqomah.setObjectName("desc_iqomah") self.group_iqomah_layout.addWidget(self.desc_iqomah, 0, 0, 1, 2) # self.check_iqomah_dialog = QCheckBox(self.group_iqomah) # self.check_iqomah_dialog.setObjectName("check_iqomah_dialog") # self.check_iqomah_dialog.setChecked( # settings.reminder_iqomah['dialog_enabled'] == '1') self.lbl_timeafterathan = QLabel(self.group_iqomah) self.lbl_timeafterathan.setObjectName("lbl_timeafterathan") # self.desc_iqomah_method = QLabel(self.group_iqomah) # self.desc_iqomah_method.setObjectName("desc_iqomah_method") self.verticalLayout.addWidget(self.group_iqomah) self.group_iqomah_layout.addWidget(self.lbl_timeafterathan, 1, 1, 1, 1) # self.group_iqomah_layout.addWidget(self.desc_iqomah_method, 8, 0, 1, 1) # self.group_iqomah_layout.addWidget(self.check_iqomah_dialog, 9, 0, 1, 1) # self.group_iqomah_layout.addWidget(self.check_iqomah_notification, 10, 0, 1, 2) self.group_custom = QGroupBox(self.scrollAreaWidgetContents) self.group_custom.setObjectName("group_custom") self.gridLayout_6 = QGridLayout(self.group_custom) self.gridLayout_6.setObjectName("gridLayout_6") self.desc_custom = QLabel(self.group_custom) self.desc_custom.setObjectName("desc_custom") self.gridLayout_6.addWidget(self.desc_custom, 0, 0, 1, 1) self.verticalLayout.addWidget(self.group_custom) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.layout_reminders.addWidget(self.scrollArea, 0, 0, 1, 1) self.tabWidget.addTab(self.tab_reminders, "") self.gridLayout.addWidget(self.tabWidget, 0, 0, 1, 1) self.setCentralWidget(self.centralwidget) self.tabWidget.setCurrentIndex(0) self.tabWidget.setTabText( self.tabWidget.indexOf(self.tab_location), _translate("SettingsWindow", "Location")) self.group_athan.setTitle(_translate("SettingsWindow", "Athan")) # self.desc_athan_method.setText(_translate("SettingsWindow", "Method of reminder")) self.desc_athan.setText(_translate("SettingsWindow", "Enable/disable athan reminder")) # self.check_athan_dialog.setText(_translate("SettingsWindow", "Pop up dialog")) # self.check_athan_notification.setText(_translate("SettingsWindow", "Pop up notification")) self.group_iqomah.setTitle(_translate("SettingsWindow", "Iqomah")) # self.check_iqomah_notification.setText(_translate("SettingsWindow", "Pop up notification")) self.desc_iqomah.setText(_translate("SettingsWindow", "Enable/disable iqomah reminder")) # self.check_iqomah_dialog.setText(_translate("SettingsWindow", "Pop up dialog")) self.lbl_timeafterathan.setText(_translate("SettingsWindow", "Time after Athan")) # self.desc_iqomah_method.setText(_translate("SettingsWindow", "Method of reminder")) self.group_custom.setTitle(_translate("SettingsWindow", "Custom")) self.desc_custom.setText(_translate("SettingsWindow", "Coming Soon!")) self.tabWidget.setTabText( self.tabWidget.indexOf(self.tab_reminders), _translate("SettingsWindow", "Reminders")) QMetaObject.connectSlotsByName(self)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) #---------------------------------------------------------------------- #----------------------------------GUI--------------------------------- #---------------------------------------------------------------------- self.setWindowTitle("Camera") #------------------------------Camera ui------------------------------- cameraimageContainer = QGroupBox("Camera View") cameraimageLayout = QGridLayout() #-------------------------Camera Operation Buttons--------------------- self.pictureButton = QPushButton("Snap picture") #This is the button for taking a single picture and saving it self.pictureButton.clicked.connect(lambda: self.takepicture()) self.singleframeButton = QPushButton("Single Frame") #This is the button for displaying a single frame for ROI selection self.singleframeButton.clicked.connect(lambda: self.singleframe()) self.recordButton = QPushButton() #Button for recording for undefined number of frames! self.recordButton.setText("Record") self.recordButton.setCheckable(True) self.recordButton.clicked.connect(lambda: self.record_enable()) self.timedButton = QPushButton("Timed video") #This is the option of recording for a preset time period/number of frames self.timedButton.clicked.connect(lambda: self.timedvideo()) self.duration = QLineEdit() self.liveButton = QPushButton() #Button for showing a live feed self.liveButton.setCheckable(True) self.liveButton.setText("Live") self.liveButton.clicked.connect(self.live_enabled) self.liveButton.clicked.connect(self.live_feed_enable) self.roi_selectionButton = QPushButton() self.roi_selectionButton.setText("ROI selection") self.roi_selectionButton.setCheckable(True) self.roi_selectionButton.clicked.connect(self.roi_selection_pressed) #------------------------------Settings--------------------------- camerasettingsContainer = QGroupBox("Settings") camerasettingsLayout = QGridLayout() ''' Adding comboboxes for all camera settings. Most are specific for the hamamatsu orca flash 4 and will not work when used with other cameras (such as the democam). In the future maybe better to generate these settings based on available micromanager setting instead of hardcoding! ''' self.camBox = QComboBox() ''' For connecting to a camera! ''' self.camBox.setGeometry(QRect(40, 40, 491, 31)) self.camBox.setObjectName(("Camera")) self.camBox.addItem("Hamamatsu") self.camBox.addItem("Democam") self.camBox.activated[str].connect(self.set_cam) camerasettingsLayout.addWidget(self.camBox,0,0) self.disconnectButton = QPushButton() ''' Disconnect from the camera using the close_cam function in the backend ''' self.disconnectButton.setText("Disconnect") self.disconnectButton.clicked.connect(lambda: self.disconnect()) camerasettingsLayout.addWidget(self.disconnectButton,1,0) self.trigBox = QComboBox() ''' Internal is the camera free running mode, external is external triggering mode. I do not know what software means exactly, it might be a start trigger mode (trigger into free running) but I'll have to see ''' self.trigBox.setGeometry(QRect(40, 40, 491, 31)) self.trigBox.setObjectName(("Trigger Source")) self.trigBox.addItem("INTERNAL") self.trigBox.addItem("EXTERNAL") self.trigBox.addItem("SOFTWARE") self.trigBox.activated[str].connect(self.set_trigger_method) camerasettingsLayout.addWidget(self.trigBox,0,1) self.trig_activeBox = QComboBox() ''' This is for selecting what type of triggering method to use. ''' self.trig_activeBox.setGeometry(QRect(40, 40, 491, 31)) self.trig_activeBox.setObjectName(("Trigger Active Edge")) self.trig_activeBox.addItem("SYNCREADOUT") self.trig_activeBox.addItem("EDGE") self.trig_activeBox.addItem("LEVEL") self.trig_activeBox.activated[str].connect(self.set_trigger_active) camerasettingsLayout.addWidget(self.trig_activeBox,1,1) self.binBox = QComboBox() ''' Binning effectively lowers the resolution while keeping sensitity high. Could be usefull in some scenarios. ''' self.binBox.setGeometry(QRect(40, 40, 491, 31)) self.binBox.setObjectName(("Binning")) self.binBox.addItem("1x1") self.binBox.addItem("2x2") self.binBox.addItem("4x4") self.binBox.activated[str].connect(self.set_binning) camerasettingsLayout.addWidget(self.binBox,0,2) self.circBufferSize = QLineEdit() ''' Small widget for setting the circular buffer size! Sets size in GB. Data stream size depends on the ROI size. ''' self.dblval = QDoubleValidator() self.dblval.setRange(0,80) self.dblval.setDecimals(1) self.circBufferSize.setValidator(self.dblval) self.circBufferSize.setFixedWidth(30) self.circBufferSize.returnPressed.connect(lambda: \ self.set_circ_buffersize(float(self.circBufferSize.text()))) camerasettingsLayout.addWidget(self.circBufferSize,1,2) self.exposureBox = QGroupBox ("Exposure Time") ''' Small widget for setting the exposure time in miliseconds. ''' self.exposureLayout = QGridLayout() self.exposure_line = QLineEdit(self) self.exposure_line.setFixedWidth(60) self.exposure_line.returnPressed.connect(lambda:self.exposure_changed()) self.exposureLayout.addWidget(QLabel("Exposure time (ms)"),0,0) self.exposureLayout.addWidget(self.exposure_line,0,1) self.exposureBox.setMaximumWidth(300) self.exposureBox.setLayout(self.exposureLayout) camerasettingsLayout.addWidget(self.exposureBox,0,3,0,2) camerasettingsContainer.setMaximumHeight(100) camerasettingsContainer.setLayout(camerasettingsLayout) #------------------------------Monitoring------------------------------ monitorContainer = QGroupBox() monitorLayout = QGridLayout() self.framerate_monitor = QLabel() monitorLayout.addWidget(self.framerate_monitor,0,1) monitorLayout.addWidget(QLabel("Framerate (Hz):"),0,0) self.buffer_free_capacity_monitor = QLabel() monitorLayout.addWidget(self.buffer_free_capacity_monitor,1,1) monitorLayout.addWidget(QLabel("Buffer Capacity (ims):"),1,0) monitorContainer.setLayout(monitorLayout) monitorContainer.setMaximumWidth(200) self.monitor_timer = QTimer() self.monitor_timer.timeout.connect(lambda: self.update_monitor()) ''' I don't start the monitor_timer during initialisation, because this will create an error. I start it when connecting to a camera! ''' #------------------------------Videoscreen----------------------------- ''' Initiating an imageview object for the main videoscreen. Hiding the pre existing ROI and menubuttons. ''' self.videoWidget = pg.ImageView() self.video_item = self.videoWidget.getImageItem() self.video_item.setAutoDownsample(True) self.videoWidget.ui.roiBtn.hide() self.videoWidget.ui.menuBtn.hide() self.videoWidget.ui.normGroup.hide() self.videoWidget.ui.roiPlot.hide() self.videoWidget.autoLevels() ''' The update timer is build for setting the framerate of the imageviewer for the main screen! The .start function determines the framerate (30 ms = 33 Hz). ''' self.update_timer_live = QTimer() self.update_timer_live.timeout.connect(lambda: self.update_view()) ''' I toggle the live feed on and off by starting/stopping the update_timer_live! ''' #--------------------------setting the camera viewer layout------------ cameraimageLayout.addWidget(self.videoWidget) cameraimageContainer.setLayout(cameraimageLayout) #--------------------------master for the camera operations---------- camopContainer = QGroupBox("Operations") camopLayout = QVBoxLayout() camopContainer.setMaximumWidth(200) camopLayout.addWidget(self.pictureButton,0) camopLayout.addWidget(self.recordButton,1) camopLayout.addWidget(self.timedButton,2) camopLayout.addWidget(self.liveButton,3) camopLayout.addWidget(self.singleframeButton,4) camopLayout.addWidget(self.roi_selectionButton,5) camopContainer.setLayout(camopLayout) #------------------------------Master---------------------------------- master = QGridLayout() master.addWidget(camerasettingsContainer,0,0) master.addWidget(cameraimageContainer,1,0) master.addWidget(monitorContainer,0,1) master.addWidget(camopContainer,1,1) self.setLayout(master) #-----------------------------Startup---------------------------------- self.no_cam_initiated()
def createCurveIcons(self): pix = QPixmap(self.m_iconSize) painter = QPainter() gradient = QLinearGradient(0, 0, 0, self.m_iconSize.height()) gradient.setColorAt(0.0, QColor(240, 240, 240)) gradient.setColorAt(1.0, QColor(224, 224, 224)) brush = QBrush(gradient) # The original C++ code uses undocumented calls to get the names of the # different curve types. We do the Python equivalant (but without # cheating). curve_types = [ (n, c) for n, c in QEasingCurve.__dict__.items() if isinstance(c, QEasingCurve.Type) and c != QEasingCurve.Custom ] curve_types.sort(key=lambda ct: ct[1]) painter.begin(pix) for curve_name, curve_type in curve_types: painter.fillRect(QRect(QPoint(0, 0), self.m_iconSize), brush) curve = QEasingCurve(curve_type) if curve_type == QEasingCurve.BezierSpline: curve.addCubicBezierSegment(QPointF(0.4, 0.1), QPointF(0.6, 0.9), QPointF(1.0, 1.0)) elif curve_type == QEasingCurve.TCBSpline: curve.addTCBSegment(QPointF(0.0, 0.0), 0, 0, 0) curve.addTCBSegment(QPointF(0.3, 0.4), 0.2, 1, -0.2) curve.addTCBSegment(QPointF(0.7, 0.6), -0.2, 1, 0.2) curve.addTCBSegment(QPointF(1.0, 1.0), 0, 0, 0) painter.setPen(QColor(0, 0, 255, 64)) xAxis = self.m_iconSize.height() / 1.5 yAxis = self.m_iconSize.width() / 3.0 painter.drawLine(0, xAxis, self.m_iconSize.width(), xAxis) painter.drawLine(yAxis, 0, yAxis, self.m_iconSize.height()) curveScale = self.m_iconSize.height() / 2.0 painter.setPen(Qt.NoPen) # Start point. painter.setBrush(Qt.red) start = QPoint(yAxis, xAxis - curveScale * curve.valueForProgress(0)) painter.drawRect(start.x() - 1, start.y() - 1, 3, 3) # End point. painter.setBrush(Qt.blue) end = QPoint(yAxis + curveScale, xAxis - curveScale * curve.valueForProgress(1)) painter.drawRect(end.x() - 1, end.y() - 1, 3, 3) curvePath = QPainterPath() curvePath.moveTo(QPointF(start)) t = 0.0 while t <= 1.0: to = QPointF(yAxis + curveScale * t, xAxis - curveScale * curve.valueForProgress(t)) curvePath.lineTo(to) t += 1.0 / curveScale painter.setRenderHint(QPainter.Antialiasing, True) painter.strokePath(curvePath, QColor(32, 32, 32)) painter.setRenderHint(QPainter.Antialiasing, False) item = QListWidgetItem() item.setIcon(QIcon(pix)) item.setText(curve_name) self.m_ui.easingCurvePicker.addItem(item) painter.end()
class LabelCanvas(QWidget): def __init__(self, statusbar=None, labelCoordinates=None, labelQLabel=None, labelEdit=None): super(LabelCanvas, self).__init__() self.statusbar = statusbar self.labelCoordinates = labelCoordinates self.labelEdit = labelEdit self.labelQLabel = labelQLabel if self.labelQLabel: self.labelQLabel.hide() if self.labelEdit: self.labelEdit.hide() self.labelEdit.returnPressed.connect(self.labelEditEnterPress) self.setMouseTracking(True) self.setFocusPolicy(Qt.WheelFocus) self.painter = QPainter() self.scaleRate = 0.2 self.pixmap = QPixmap('icon/sample.jpg') self.pmapRect = self.pixmap.rect() self.pmapShowAreaRect = self.pixmap.rect() self.drag = False self.labels = () self.mousex = 0 self.mousey = 0 self.labels = [] self.templabel = [] self.labeling = False self.labelsRect = [] self.deleteRects = [] self.textRects = [] def loadPixmap(self, pixmap, labels=None): self.pixmap = pixmap self.pmapRect = pixmap.rect() self.pmapShowAreaRect = pixmap.rect() self.labels.clear() if labels: self.labels.extend(labels) self.repaint() def paintEvent(self, e): self.painter.begin(self) # 绘制图片内容 self.painter.drawPixmap(self.rect(), self.pixmap, self.pmapShowAreaRect) # 绘制图片区域预览 self.painter.setPen(QColor(0, 0, 0)) scale = min(self.width() / self.pixmap.width() / 5, self.height() / self.pixmap.height() / 5) self.pmapPreRect = QRect(0, 0, self.pixmap.width() * scale, self.pixmap.height() * scale) margin = int(min(self.width(), self.height()) / 16) self.pmapPreRect.moveTopRight(QPoint(self.width() - margin, margin)) self.painter.drawRect(self.pmapPreRect) # 绘制图片展示区域预览 self.painter.setPen(QColor(255, 0, 0)) pmapprerect = self.pmapPreRect.getRect() pmapshowarearect = self.pmapShowAreaRect.getRect() x = pmapprerect[0] + self.pmapPreRect.width( ) * pmapshowarearect[0] / self.pixmap.width() y = pmapprerect[1] + self.pmapPreRect.height( ) * pmapshowarearect[1] / self.pixmap.height() w = scale * self.pmapShowAreaRect.width() h = scale * self.pmapShowAreaRect.height() self.pmapShowAreaPreRect = QRect(x, y, w, h) self.painter.drawRect(self.pmapShowAreaPreRect) self.dragAreaRect = QRect( self.pmapPreRect.x() - self.pmapShowAreaPreRect.width(), self.pmapPreRect.y() - self.pmapShowAreaPreRect.height(), self.pmapShowAreaPreRect.width() + self.pmapPreRect.width(), self.pmapShowAreaPreRect.height() + self.pmapPreRect.height()) # 绘制缩放中心点标线 self.painter.setPen(QColor(255, 0, 0)) self.painter.drawLine(self.width() / 3, self.height() / 2, self.width() / 3 * 2, self.height() / 2) self.painter.drawLine(self.width() / 2, self.height() / 3, self.width() / 2, self.height() / 3 * 2) # 绘制鼠标位置标线 if self.labeling: self.painter.setPen(QColor(0, 0, 0)) self.painter.drawLine(self.mousex, 0, self.mousex, self.height()) self.painter.drawLine(0, self.mousey, self.width(), self.mousey) # 绘制正在编辑中的label位置 if self.templabel: for i in range(int(len(self.templabel) / 2)): imagex, imagey = self.templabel[0 + 2 * i], self.templabel[1 + 2 * i] if self.pmapShowAreaRect.contains(imagex, imagey): widgetx, widgety = self.imageXY2WidgetXY(imagex, imagey) self.painter.setPen(QPen(Qt.red, 5)) self.painter.drawPoint(widgetx, widgety) pen = QPen(Qt.black, 2, Qt.SolidLine) pen.setStyle(Qt.DashDotDotLine) self.painter.setPen(pen) self.painter.drawLine(widgetx, 0, widgetx, self.height()) self.painter.drawLine(0, widgety, self.width(), widgety) # 绘制已标记内容 self.deleteRects.clear() self.textRects.clear() self.painter.setPen(QColor(168, 34, 3)) self.painter.setFont(QFont('Decorative', 12)) metrics = self.painter.fontMetrics() deleteRectWidth, deleteRectHeight = metrics.height( ) * 1.2, metrics.height() * 1.2 separatorheight = margin / 10 pmapprerect = self.pmapPreRect.getRect() topRightx, topRighty = self.width( ) - margin, pmapprerect[1] + pmapprerect[3] + margin / 4 for i in range(len(self.labels)): label = self.labels[i] # 绘制文字展示信息 text = label[4] deleteRect = QRect( topRightx - deleteRectWidth, topRighty + (deleteRectHeight + separatorheight) * i, deleteRectWidth, deleteRectHeight) self.painter.drawRect(deleteRect) self.painter.drawLine(deleteRect.topLeft(), deleteRect.bottomRight()) self.painter.drawLine(deleteRect.topRight(), deleteRect.bottomLeft()) self.deleteRects.append(deleteRect) deleterect = deleteRect.getRect() textWidth, textHeight = metrics.width(text), metrics.height() textRect = QRect(deleterect[0] - textWidth - metrics.height(), deleterect[1], textWidth + metrics.height(), deleterect[3]) self.painter.drawRect(textRect) self.painter.drawText(textRect, Qt.AlignCenter, text) self.textRects.append(textRect) # 在图片上绘制标签矩形框 labelPixmapX, labelPixmapY, labelPixmapWidth, labelPixmapHeight = label[: 4] labelPixmapRect = QRect(labelPixmapX, labelPixmapY, labelPixmapWidth, labelPixmapHeight) intersectedRect = self.pmapShowAreaRect.intersected( labelPixmapRect) if intersectedRect: pixmapTopLeftPoint, pixmapBottomRightPoint = intersectedRect.topLeft( ), intersectedRect.bottomRight() widgetTopLeftPointX, widgetTopLeftPointY = self.imageXY2WidgetXY( pixmapTopLeftPoint.x(), pixmapTopLeftPoint.y()) widgetTopLeftPoint = QPoint(widgetTopLeftPointX, widgetTopLeftPointY) widgetBottomRightPointX, widgetBottomRightPointY = self.imageXY2WidgetXY( pixmapBottomRightPoint.x(), pixmapBottomRightPoint.y()) widgetBottomRightPoint = QPoint(widgetBottomRightPointX, widgetBottomRightPointY) labelRect = QRect(widgetTopLeftPoint, widgetBottomRightPoint) self.painter.drawRect(labelRect) # 绘制标签名 labelrect = labelRect.getRect() textRect1 = QRect(labelrect[0], labelrect[1] - textHeight, textWidth, textHeight) # self.painter.drawRect(textRect1) self.painter.drawText(textRect1, Qt.AlignCenter, text) self.painter.end() # 将图片中像素坐标转化为控件坐标 def imageXY2WidgetXY(self, imagex, imagey): pmapshowarearect = self.pmapShowAreaRect.getRect() widgetx = (imagex - pmapshowarearect[0]) / pmapshowarearect[2] * self.width() widgety = (imagey - pmapshowarearect[1]) / pmapshowarearect[3] * self.height() return widgetx, widgety # 恢复图片初加载状态 def restart(self): self.pmapRect = self.pixmap.rect() self.pmapShowAreaRect = self.pixmap.rect() self.repaint() # 初始化一个新的标签 def label(self): self.templabel.clear() self.labeling = True if self.labelQLabel: self.labelQLabel.setText('') self.labelQLabel.show() self.status('开始创建标签', delay=500) self.repaint() # 移除最后一次添加的像素点 def undo(self): self.removeTempPoint() # 返回标签内容 def save(self): self.clearStatus() return self.labels def clearStatus(self): if self.labelQLabel: self.labelQLabel.hide() if self.labelEdit: self.labelEdit.hide() if self.templabel: self.templabel.clear() self.labeling = False self.repaint() # 添加标记点 def addTempPoint(self, x, y): if self.labelQLabel.isHidden(): self.labelQLabel.show() self.templabel.append(x) self.templabel.append(y) self.statusLabel('创建标签->' + str(self.templabel)) if len(self.templabel) == 4: self.statusLabel('标签内容为->' + str(self.templabel) + ' 请输入标签名->') self.labeling = False self.labelEdit.setText('') self.labelEdit.setFocus() self.labelEdit.show() self.repaint() # 移除标记点 def removeTempPoint(self): if self.templabel: self.templabel = self.templabel[:-2] self.repaint() self.labelEdit.setText('') self.labelEdit.hide() self.labelQLabel.setText('标签内容->' + str(self.templabel)) if len(self.templabel) == 0: self.labelQLabel.hide() # 监听滚轮事件 def wheelEvent(self, event): if event.angleDelta: if event.angleDelta().y() / 120 >= 1: self.enlargeByCenter() else: self.narrowByCenter() # 监听鼠标双击事件 def mouseDoubleClickEvent(self, event): if self.labeling: if len(self.templabel) >= 4: self.label() self.status('标记错误,已重置', delay=800) return pointx = math.ceil(self.pmapShowAreaRect.getRect()[0] + (self.pmapShowAreaRect.width() * event.pos().x() / self.width())) pointy = math.ceil(self.pmapShowAreaRect.getRect()[1] + (self.pmapShowAreaRect.height() * event.pos().y() / self.height())) if self.pmapRect.contains(pointx, pointy): self.addTempPoint(pointx, pointy) else: self.status('请选择图片区域', delay=500) # 监听键盘ESC键按下 def keyPressEvent(self, event): if event.key() == Qt.Key_Escape: if self.labelQLabel: self.labelQLabel.hide() if self.labelEdit: self.labelEdit.hide() if self.templabel: self.templabel.clear() self.labeling = False self.repaint() def labelEditEnterPress(self): self.labelEdit.hide() if self.labelQLabel: self.labelQLabel.hide() labelText = self.labelEdit.text() templabelrect = [ min(self.templabel[0], self.templabel[2]), min(self.templabel[1], self.templabel[3]), abs(self.templabel[0] - self.templabel[2]), abs(self.templabel[1] - self.templabel[3]), '默认标签名' if labelText.strip() == '' else labelText.strip() ] self.status('标签创建成功->' + str(templabelrect), delay=1000) self.labels.append(templabelrect) self.templabel.clear() self.labeling = False self.repaint() # 监听鼠标按下事件 def mousePressEvent(self, event): if self.pmapShowAreaPreRect.contains(event.pos().x(), event.pos().y()): self.drag = True elif self.pmapPreRect.contains(event.pos().x(), event.pos().y()): pmapprerect = self.pmapPreRect.getRect() pmaprect = self.pmapRect.getRect() scale = pmaprect[2] / pmapprerect[2] ximage = (event.pos().x() - pmapprerect[0]) * scale yimage = (event.pos().y() - pmapprerect[1]) * scale self.pmapShowAreaRect.moveCenter(QPoint(ximage, yimage)) self.repaint() else: self.labelTextClickCheck(event.pos().x(), event.pos().y()) # 鼠标点击到标签逻辑 def labelTextClickCheck(self, widgetx, widgety): for i in range(len(self.textRects)): if self.textRects[i].contains(widgetx, widgety): self.status(str(self.labels[i]), delay=1000) labelx, labely, labelwidth, labelheight = self.labels[i][:4] self.pmapShowAreaRect.moveCenter( QRect(labelx, labely, labelwidth, labelheight).center()) self.repaint() return for i in range(len(self.deleteRects)): if self.deleteRects[i].contains(widgetx, widgety): self.labels.pop(i) self.repaint() return # 鼠标移动事件 def mouseMoveEvent(self, event): pointx = math.ceil(self.pmapShowAreaRect.getRect()[0] + (self.pmapShowAreaRect.width() * event.pos().x() / self.width())) pointy = math.ceil(self.pmapShowAreaRect.getRect()[1] + (self.pmapShowAreaRect.height() * event.pos().y() / self.height())) self.labelCoordinates.setText('X: %s Y: %s' % (pointx, pointy)) if self.drag and self.dragAreaRect.contains(event.pos().x(), event.pos().y()): pmapprerect = self.pmapPreRect.getRect() pmaprect = self.pmapRect.getRect() scale = pmaprect[2] / pmapprerect[2] ximage = (event.pos().x() - pmapprerect[0]) * scale yimage = (event.pos().y() - pmapprerect[1]) * scale self.pmapShowAreaRect.moveCenter(QPoint(ximage, yimage)) self.repaint() else: if self.pmapPreRect.contains(event.pos().x(), event.pos().y()): self.mousex, self.mousey = 0, 0 self.repaint() else: self.mousex, self.mousey = event.pos().x(), event.pos().y() self.repaint() def mouseReleaseEvent(self, event): self.drag = False # 以图片中心放大图片 def enlargeByCenter(self): pmapshowarearect = self.pmapShowAreaRect.getRect() pmaprect = self.pmapRect.getRect() if pmapshowarearect[2] <= pmaprect[2] / 20 or pmapshowarearect[ 3] <= pmaprect[3] / 20: return self.pmapShowAreaRect.adjust( self.pmapShowAreaRect.width() * self.scaleRate, self.pmapShowAreaRect.height() * self.scaleRate, -self.pmapShowAreaRect.width() * self.scaleRate, -self.pmapShowAreaRect.height() * self.scaleRate) self.repaint() # 以图片中心缩放图片 def narrowByCenter(self): pmapshowarearect = self.pmapShowAreaRect.getRect() pmaprect = self.pmapRect.getRect() if pmapshowarearect[2] >= pmaprect[2] or pmapshowarearect[ 3] >= pmaprect[3]: return self.pmapShowAreaRect.adjust( -self.pmapShowAreaRect.width() * self.scaleRate / (1 - 2 * self.scaleRate), -self.pmapShowAreaRect.height() * self.scaleRate / (1 - 2 * self.scaleRate), self.pmapShowAreaRect.width() * self.scaleRate / (1 - 2 * self.scaleRate), self.pmapShowAreaRect.height() * self.scaleRate / (1 - 2 * self.scaleRate)) self.repaint() def statusLabel(self, message): if self.labelQLabel: self.labelQLabel.setText(message) def status(self, message, delay=-1): if self.statusbar: self.statusbar.showMessage(message, delay) def labelCoord(self, message): if self.labelCoordinates: self.labelCoordinates.setText(message) def setStatusBar(self, statusbar): self.statusbar = statusbar def setlabelCoordinates(self, labelCoordinates): self.labelCoordinates = labelCoordinates
def drawBackground(self, painter, rect): painter.fillRect( QRect(rect["x"], rect["y"], rect["width"], rect["height"]), QColor(self.ST_BACKGROUND_COLOR))