def testNoIntersectBounding(self): '''QRect | QRect for non-intersecting QRects Non-intersecting QRects return a greater QRect for operator |''' rect1 = QRect(10, 10, 5, 5) rect2 = QRect(20, 20, 5, 5) rect3 = rect1 | rect2 self.assertEqual(rect3, QRect(10, 10, 15, 15))
def paint(self, painter, option, index): rect = option.rect movie = index.data(Qt.UserRole) painter.setOpacity(0.7) if option.state & QStyle.State_Selected: painter.drawRect(rect) # draw poster background painter.setPen(self.outline) painter.setBrush(self.backgoundBrush) painter.drawRect(rect) # draw poster pixmap = QPixmap(movie.poster).scaled(rect.width() - 25, rect.height() - 50, Qt.KeepAspectRatio, Qt.SmoothTransformation) posterRect = QRect(rect.x() + 15, rect.y() + 15, pixmap.width(), pixmap.height()) painter.drawPixmap(posterRect, pixmap) # draw movie title titleRect = QRect(rect.x(), rect.bottom() - 30, rect.width(), rect.height()) releaseText = "({})".format( movie.releaseDate.split("-")[0]) if movie.releaseDate else "" painter.drawText(titleRect, Qt.AlignHCenter, u"{0} {1}".format(movie.name, releaseText))
def testNoIntersect(self): '''QRect & QRect for non-intersecting QRects Non-intersecting QRects return a 'null' QRect for operator &''' rect1 = QRect(10, 10, 5, 5) rect2 = QRect(20, 20, 5, 5) rect3 = rect1 & rect2 self.assertEqual(rect3, QRect())
def testNullRectIntersectBounding(self): #QRect | QRect for null rects rect1 = QRect() rect2 = QRect() rect3 = rect1 & rect2 self.assertEqual(rect3, rect1) self.assertEqual(rect3, rect2)
def _draw_horizontal_ruler(self, painter, text, y_value, color): y = y_value * self.y_factor pen = QPen() pen.setCapStyle(Qt.SquareCap) pen.setColor(color) qp = QPainterPath() r = QRect(1,1,1000,1000) bb = painter.boundingRect(r,Qt.AlignLeft,text) bb = QRect(self.x_base,self.y_base - y - bb.height(), bb.width() + 2, bb.height()) # print("{} {} {} {}".format(bb.x(),bb.y(),bb.width(),bb.height())) fill_color = QColor(0,0,0) fill_color.setAlpha(128) brush = QBrush(fill_color) painter.fillRect(bb,brush) qp.moveTo(self.x_base,self.y_base - y) qp.lineTo(self.total_width + self.x_base, self.y_base - y) painter.setPen(pen) painter.drawPath(qp) text_pen = QPen() text_pen.setCapStyle(Qt.RoundCap) text_pen.setColor(color) # alpha=255=fully opaque text_pen.setWidth(1) painter.setPen(text_pen) painter.drawText(self.x_base,self.y_base - y - 5,text)
def _draw_selected_items_in_series(self, painter): fm = painter.fontMetrics() pen = QPen() pen.setWidth(1) pen.setColor(Qt.GlobalColor.white) painter.setPen(pen) # We assume all series have the very same number of values # and all values on the same index are drawn on the same X # coordinate ndx_serie = self.best_serie_intra_ndx aesthetic_shift = 5 if ndx_serie is not None: to_draw = [] for i in range(len(self.data)): x, y = self._item_coordinates_lines(i, ndx_serie) #mainlog.debug("{} {}".format(ndx_serie,i)) v = self.data[i][ndx_serie] text = str(int(v)) to_draw.append( (self.y_base - y, text) ) last_y = 100000 for y, text in sorted( to_draw, key=lambda z : z[0], reverse=True): r = QRect(x + aesthetic_shift,0,1000,1000) bb = painter.boundingRect(r,Qt.AlignLeft,text) if bb.right() > self.width(): x = x - bb.width() - 2*aesthetic_shift# left align if y + bb.height() > last_y: y = last_y - bb.height() fill_color = QColor(16, 16, 48) fill_color.setAlpha(196) brush = QBrush(fill_color) margin = 2 r = QRect(x + aesthetic_shift - margin, y - aesthetic_shift - bb.height() - margin, bb.width() + 2*margin, bb.height() + 2*margin) painter.fillRect(r, brush) painter.drawText(x + aesthetic_shift, y - aesthetic_shift, text) last_y = y x, y = self._item_coordinates_lines(0, ndx_serie) qp = QPainterPath() qp.moveTo(x, self.y_base) qp.lineTo(x, self.y_base - self.total_height) painter.drawPath(qp)
def testConstructorQPoint(self): topLeft = QPoint(3, 0) bottomRight = QPoint(0, 3) rect1 = QRect(topLeft, bottomRight) rect2 = QRect(topLeft, bottomRight) self.assertEqual(rect1, rect2)
def _draw_legend2(self, painter, labels): text_pen = QPen() text_pen.setCapStyle(Qt.RoundCap) text_pen.setColor(QColor(200, 200, 200)) # alpha=255=fully opaque text_pen.setWidth(1) highlighted_text_pen = QPen() highlighted_text_pen.setColor(QColor(255, 255, 255)) # alpha=255=fully opaque highlighted_text_pen.setWidth(1) line_pen = QPen() line_pen.setCapStyle(Qt.RoundCap) line_pen.setColor(QColor(200, 200, 200)) # alpha=255=fully opaque line_pen.setWidth(2) row = col = 0 self.legend_labels_bounding_boxes = [] for data_ndx, label in sorted( zip(range(len(labels)),labels), key=lambda a:a[1]): if label: # One can hide a series' legend by using a blank label x = self.margin + col * self.max_legend_label_width + 3 y = self.legend_y_start + row * self.text_height # Draw coloured line line_pen.setColor(self.graph_colors[data_ndx % len(self.graph_colors)]) # alpha=255=fully opaque painter.setPen(line_pen) if data_ndx == self.ndx_best_serie: r = QRect(x-3, y-self.text_height+3, self.max_legend_label_width, self.text_height) painter.drawRect(r) painter.setPen(highlighted_text_pen) else: painter.drawLine(x,y+3,x+self.max_legend_label_width - 6,y + 3) painter.setPen(text_pen) painter.drawText(x,y, label) # Remember text bounding box r = QRect(x,y - self.text_height, self.max_legend_label_width, self.text_height) bb = painter.boundingRect(r,Qt.AlignLeft,label) # if label == 'TV': # painter.drawRect(r) self.legend_labels_bounding_boxes.append( (data_ndx,r) ) if not (col < self.legend_labels_per_line - 1): col = 0 row += 1 else: col += 1
def _calculate_bounds(self): width = self.width() height = self.height() # Hue palette self._hue_rect = QRect(width - self._hue_width, 0, self._hue_width, height) # Shades palette self._shades_rect = QRect(0, 0, width - (self._hue_width + self._gap), height)
def testEqual(self): '''QRect == QRect Note: operator == must be working as it's the main check for correctness''' rect1 = QRect() rect2 = QRect() self.assertEqual(rect1, rect2) rect1 = QRect(0, 4, 100, 300) rect2 = QRect(0, 4, 100, 300) self.assertEqual(rect1, rect2)
def _setupPainterPath(self): painter_path = QPainterPath() painter_path.moveTo(0, 15) #left painter_path.lineTo(0, 0) #up painter_path.lineTo(self.width() - 1, 0) # right painter_path.lineTo(self.width() - 1, 15) # down painter_path.arcTo(QRect(self.width() - 6, 15, 5, 4), 0, -90) # control point1, cp2, destPoint painter_path.lineTo(5, 19) # left painter_path.arcTo(QRect(1, 15, 5, 4), 270, -90) #arc left up painter_path.closeSubpath() self._painter_path = painter_path
def _draw_box_under_text(self,painter,x,y,text): r = QRect(1,1,1000,1000) bb = painter.boundingRect(r,Qt.AlignLeft,text) bb = QRect(x,y - bb.height() +2 , bb.width() + 2, bb.height()) # print("{} {} {} {}".format(bb.x(),bb.y(),bb.width(),bb.height())) fill_color = QColor(0,0,0) fill_color.setAlpha(170) brush = QBrush(fill_color) painter.fillRect(bb,brush)
def initializeComposition(self): """Main Dialog""" self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) self.setFocusPolicy(Qt.StrongFocus) self.setFrameStyle(QFrame.StyledPanel | QFrame.Raised) #Font will appear in buttons self.setFont( QFont(self.options.getQuizFont(), self.options.getQuizFontSize())) desktop = QApplication.desktop().screenGeometry() self.setGeometry( QRect(desktop.width() - H_INDENT, desktop.height() - V_INDENT, D_WIDTH, D_HEIGHT)) self.setStyleSheet("QWidget { background-color: rgb(255, 255, 255); }") """Info dialog""" self.info.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) self.info.setFrameStyle(QFrame.StyledPanel | QFrame.Raised) self.info.setGeometry( QRect(desktop.width() - H_INDENT - I_WIDTH - I_INDENT, desktop.height() - V_INDENT, I_WIDTH, I_HEIGHT)) self.info.setFixedSize(I_WIDTH, I_HEIGHT) self.info.setStyleSheet( "QWidget { background-color: rgb(255, 255, 255); }") """Verbose info dialog""" self.allInfo.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) self.allInfo.setFrameStyle(QFrame.StyledPanel | QFrame.Raised) self.allInfo.setGeometry( QRect(desktop.width() - H_INDENT - I_WIDTH - I_INDENT, desktop.height() - V_INDENT, I_WIDTH, I_HEIGHT)) self.allInfo.setStyleSheet( "QWidget { background-color: rgb(255, 255, 255); }") """Session message""" self.status.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) self.status.setFrameStyle(QFrame.StyledPanel | QFrame.Raised) self.status.setGeometry( QRect( desktop.width() - H_INDENT, desktop.height() - V_INDENT - S_HEIGHT - S_INDENT - S_CORRECTION, S_WIDTH, S_HEIGHT)) self.status.setStyleSheet( "QWidget { background-color: rgb(255, 255, 255); }") self.setMask(roundCorners(self.rect(), 5)) self.status.setMask(roundCorners(self.status.rect(), 5))
def set_shape(self, width, height): ''' ANSWER has round, disjoint sides - does not fit in a polygon ''' self.width, self.height = width, height point = width / 2.85 path = QPainterPath() left = QRect(0, 0, point, height) right = QRect(width - point, 0, point, height) path.arcMoveTo(left, 125) path.arcTo(left, 125, 110) path.arcMoveTo(right, -55) path.arcTo(right, -55, 110) path.moveTo(width, height) self.setPath(path) super(DecisionAnswer, self).set_shape(width, height)
def paint(self, painter, point): painter.save() size = QSize(self.width(), self.height()) painter.setBrush(self.bg_color) painter.drawRoundedRect(QRect(point, size), BLOCK_RADIUS, BLOCK_RADIUS) # Рисуем столбцы p = QPoint(point) + QPoint(0, BLOCK_RADIUS) for c in self.columns: p += QPoint(BLOCK_RADIUS, 0) c.paint(painter, p) p += QPoint(c.width(), 0) # Рисуем левые порты if len(self.left_pins): p = QPoint(point) p += QPoint(0, size.height() / (len(self.left_pins) + 1)) for lp in self.left_pins: lp.paint(painter, p) p += QPoint(0, size.height() / (len(self.left_pins) + 1)) # Рисуем правые порты if len(self.right_pins): p = QPoint(point) p += QPoint(size.width(), size.height() / (len(self.right_pins) + 1)) for rp in self.right_pins: rp.paint(painter, p) p += QPoint(0, size.height() / (len(self.right_pins) + 1)) painter.restore()
def __layoutActions(self): if self._layout == None: self._layout = dict() actions = self.actions() count = len(actions) angleStep = 2.0 * math.pi / float(count) angle = 0 fontMetrics = QtGui.QFontMetrics(self.font()) radius = 120 bounds = QRect() for a in actions: r = fontMetrics.boundingRect(a.text()).adjusted(-8, -8, 8, 8) r = r.translated(radius * math.cos(angle), radius * math.sin(angle)) r = r.translated(-r.width() / 2, -r.height() / 2) r = r.translated(self.width() / 2, self.height() / 2) self._layout[a] = r bounds |= r angle += angleStep bounds = bounds.adjusted(-self._lineWidth, -self._lineWidth, self._lineWidth, self._lineWidth) for a in self._layout.keys(): r = self._layout[a] r.translate(-bounds.x(), -bounds.y()) self.resize(bounds.width(), bounds.height())
def testDrawTextWithRect(self): # bug #225 rect = QRect(100, 100, 100, 100) newRect = self.painter.drawText(rect, Qt.AlignCenter | Qt.TextWordWrap, self.text) self.assert_(isinstance(newRect, QRect))
def __init__(self, define_path='', define_type=None): super(MTTFilterFileDialog, self).__init__(get_maya_window()) self.supported_node_type = sorted([ node_type for (node_type, nice, attr) in MTTSettings.SUPPORTED_TYPE ]) self.defined_path = (define_path if os.path.isdir(define_path) or define_path == SOURCEIMAGES_TAG else None) self.defined_type = (define_type if define_type in self.supported_node_type else None) self.path_edit = None self.filter_reset_btn = None self.filter_line = None self.parent_folder_btn = None self.files_model = None self.files_list = None self.bookmark_list = None self.bookmark_list_sel_model = None self.types = None # move window to cursor position win_geo = MTTSettings.value('FilterFileDialog/windowGeometry', QRect(0, 0, 400, 300)) self.setGeometry(win_geo) mouse_pos = QCursor.pos() mouse_pos.setX(mouse_pos.x() - (win_geo.width() * 0.5)) self.move(mouse_pos) self.__create_ui() self.filter_line.setFocus() self.on_change_root_path(self.defined_path or SOURCEIMAGES_TAG)
def paintEvent(self, pe): painter = QPainter(self) painter.save() gradient = QLinearGradient() gradient.setStart(self._grad_start) gradient.setFinalStop(self._grad_end) gradient.setColorAt(0, QColor(230, 230, 230)) gradient.setColorAt(1, QColor(247, 247, 247)) brush = QBrush(gradient) painter.setBrush(brush) pen = QPen(Qt.black) pen.setWidth(1) painter.setPen(pen) painter.drawPath(self._painter_path) painter.restore() font = QFont() font.setFamily("Tahoma") font.setPixelSize(11) font.setBold(True) pen = QPen(Qt.darkGray) painter.setPen(pen) painter.setFont(font) self_rect = QRect(self.rect()) self_rect.moveTo(self._hor_margin, self._ver_margin // 2) painter.drawText(self_rect, Qt.AlignLeft, self._text)
def paintEvent(self, pe): if self._drop_zones_shown: painter = QPainter(self.viewport( )) # See documentation to know why I draw on the viewport painter.setFont(self._titles_font) vr = self.rect() nb_drop_zones = len(self._drop_zones_titles) subr = QRect(vr) subr.setHeight(vr.height() / nb_drop_zones) for i in range(nb_drop_zones): c = self._drop_zones_colors[i] text_pen = QPen() text_pen.setColor(inverse_colors(c)) painter.setPen(text_pen) if i == self._selected_drop_zone: # mainlog.debug("selected drop zone is {}".format(i)) c = c.lighter(200) painter.setBrush(c) subr.moveTop(int(i * vr.height() / nb_drop_zones)) painter.drawRect(subr) painter.drawText( QPoint(10, int((i + 0.5) * vr.height() / nb_drop_zones)), self._drop_zones_titles[i]) return None else: return super(AnimatedTableView, self).paintEvent(pe)
def testQRectWithFull(self): '''QFontMetrics.boundingRect(QRect, ...) - all arguments''' arg = QRect(0, 0, 100, 200) rect = self.metrics.boundingRect(arg, Qt.TextExpandTabs | Qt.AlignLeft, 'PySide by INdT', 20, [1, 2, 3, 4, 5]) self.assertTrue(isinstance(rect, QRect))
def saveAsBitmap(self, fn): """ Save bar image as a jpg file. Overwrites a file already existing in filesystem. https://stackoverflow.com/questions/7451183/how-to-create-image-file\ -from-qgraphicsscene-qgraphicsview#11642517 Args: fn: Filename Returns: True on success """ size = self.size pixelsx = max(1200, size[0]) pixelsy = int(pixelsx*size[1]/size[0]) imagesize = (pixelsx, pixelsy) image = QImage(pixelsx, pixelsy, QImage.Format_ARGB32_Premultiplied) painter = QPainter(image) painter.setRenderHint(QPainter.Antialiasing) painter.setBrush(Qt.white) painter.setPen(Qt.white) painter.drawRect(QRect(0, 0, *imagesize)) targetrect = QRectF(0, 0, *imagesize) sourcerect = QRectF(0, 0, *size) self.render(painter, targetrect, sourcerect) painter.end() return image.save(fn)
def saveAsPdf(self, fn, force=False): """ Save bar image as a eps file. Args: fn: Filename force: if True, overwrites an existing file. If false, raises a RuntimeError if file already exists. """ printer = QPrinter(QPrinter.HighResolution) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(fn) printer.setFullPage(True) printer.setPageSize(QPrinter.Custom) printer.setPaperSize(QSizeF(*self.size), QPrinter.Millimeter) printer.setPageMargins(0, 0, 0, 0, QPrinter.Millimeter) painter = QPainter(printer) painter.setRenderHint(QPainter.Antialiasing) painter.setBrush(Qt.white) painter.setPen(Qt.white) painter.drawRect(QRect(0, 0, *self.size)) targetrect = QRectF(0, 0, printer.width(), printer.height()) sourcerect = QRectF(0, 0, *self.size) self.render(painter, targetrect, sourcerect) painter.end() return True
def testGetCoordsAndRect(self): rect1 = QRect(1, 2, 3, 4) self.assertEqual(rect1.getRect(), (1, 2, 3, 4)) self.assertEqual(rect1.getCoords(), (1, 2, 3, 5)) rect1 = QRectF(1, 2, 3, 4) self.assertEqual(rect1.getRect(), (1, 2, 3, 4)) self.assertEqual(rect1.getCoords(), (1, 2, 4, 6))
def __init__(self): QWidget.__init__(self) self.setGeometry(QRect(100, 100, 400, 200)) self.layout = QtGui.QGridLayout(self) #lblCorporateEventType self.lblCorporateEventType = QLabel("Type") self.layout.addWidget(self.lblCorporateEventType, 0, 0) #cmbCorporateEventType self.cmbCorporateEventType = QComboBox(self) corporateEventTypeList = DaoCorporateEvent().getCorporateEventTypeList( ) for (corporateEventType) in corporateEventTypeList: self.cmbCorporateEventType.addItem(corporateEventType[1], corporateEventType[0]) self.layout.addWidget(self.cmbCorporateEventType, 0, 1) #lblAssetName self.lblAssetName = QLabel("Asset Name") self.layout.addWidget(self.lblAssetName, 1, 0) #cmdAssetName self.cmdAssetName = QComboBox(self) assetNameList = DaoAsset().getAssetNames('EQUITY') for (assetName) in assetNameList: self.cmdAssetName.addItem(assetName[1], assetName[0]) self.layout.addWidget(self.cmdAssetName, 1, 1) #lblCustody self.lblCustody = QLabel("Custody") self.layout.addWidget(self.lblCustody, 2, 0) #cmbCustody self.cmbCustody = QComboBox(self) custodyList = DaoCustody().getCustodyList() for (row) in custodyList: self.cmbCustody.addItem(row[1], row[0]) self.layout.addWidget(self.cmbCustody, 2, 1) #lblGrossAmount self.lblGrossAmount = QLabel("Gross Amount") self.layout.addWidget(self.lblGrossAmount, 3, 0) #txtGrossAmount self.txtGrossAmount = QLineEdit(self) self.txtGrossAmount.setValidator(QDoubleValidator( 0, 99999999, 6, self)) self.layout.addWidget(self.txtGrossAmount, 3, 1) #lblPaymentDate self.lblPaymentDate = QLabel("Payment Date") self.layout.addWidget(self.lblPaymentDate, 4, 0) #cmbPaymentDate self.cmbPaymentDate = QDateEdit(self) self.cmbPaymentDate.setDisplayFormat("dd-MM-yyyy") self.cmbPaymentDate.setDate(datetime.datetime.now()) self.layout.addWidget(self.cmbPaymentDate, 4, 1) #btnAdd self.btnAdd = QPushButton("Add", self) self.layout.addWidget(self.btnAdd) #btnClear self.btnClear = QPushButton("Clear", self) self.layout.addWidget(self.btnClear) #clearEditor self.clearEditor() self.initListener()
def numberbarPaint(self, number_bar, event): """Paints the line numbers of the code file""" self.number_bar.link = [] font_metrics = self.getWidget().fontMetrics() current_line = self.getWidget().document().findBlock( self.getWidget().textCursor().position()).blockNumber() + 1 block = self.getWidget().firstVisibleBlock() line_count = block.blockNumber() painter = QPainter(self.number_bar) # TODO: second argument is color -> to settings painter.fillRect(self.number_bar.rect(), self.getWidget().palette().base()) # Iterate over all visible text blocks in the document. while block.isValid(): line_count += 1 text = str(line_count) block_top = self.getWidget().blockBoundingGeometry( block).translated(self.getWidget().contentOffset()).top() if not block.isVisible(): block = block.next() while not block.isVisible(): line_count += 1 block = block.next() continue self.number_bar.link.append((block_top, line_count)) # Check if the position of the block is out side of the visible # area. if block_top >= event.rect().bottom(): break # We want the line number for the selected line to be bold. if line_count == current_line: font = painter.font() font.setBold(True) else: font = painter.font() font.setBold(False) # line opens a block if line_count in self.hidden: text += "+" font.setUnderline(True) elif block.text().count("(") > block.text().count(")"): text += "-" font.setUnderline(True) else: font.setUnderline(False) painter.setFont(font) # Draw the line number right justified at the position of the # line. paint_rect = QRect(0, block_top, self.number_bar.width(), font_metrics.height()) painter.drawText(paint_rect, Qt.AlignLeft, text) block = block.next() painter.end()
def checkBoxRect(self, opt, editor): cb_option = QStyleOptionButton() style = QApplication.style() cb_rect = style.subElementRect(QStyle.SE_CheckBoxIndicator, cb_option, editor) cb_point = QPoint( opt.rect.x() + (opt.rect.width() - cb_rect.width()) / 2, opt.rect.y() + (opt.rect.height() - cb_rect.height()) / 2) return QRect(cb_point, cb_rect.size())
def boundingRect(self): if not self.node_from or not self.node_to: return QRect() n1 = self.node_from() n2 = self.node_to() if n1 is None or n2 is None: return QRect() node_from_pos = n1.pos() node_to_pos = n2.pos() bbox = QRect(min(node_from_pos.x(), node_to_pos.x()), min(node_from_pos.y(), node_to_pos.y()), abs(node_from_pos.x() - node_to_pos.x()), abs(node_from_pos.y() - node_to_pos.y())) return bbox
def absoluteGeometry(self): """A fix to get the element to return it's absolute geometry, instead of it's geometry relative to it's parent frame""" if self._geometry_calculated: return self._geometry if self._element.isNull(): return None elem = self._element elem_geom = QRect(elem.geometry()) elem_webframe = elem.webFrame() elem_wf_geom = QRect(elem_webframe.geometry()) elem_geom.moveTopLeft(elem_geom.topLeft() - elem_wf_geom.topLeft()) wf_parent = elem_webframe.parentFrame() while wf_parent: wf_parent_geom = wf_parent.geometry() elem_geom.moveTopLeft(elem_geom.topLeft() - wf_parent_geom.topLeft()) self._geometry = elem_geom self._geometry_calculated = True return elem_geom
def getCheckBoxRect(self, option): check_box_style_option = QStyleOptionButton() check_box_rect = QApplication.style().subElementRect( QStyle.SE_CheckBoxIndicator, check_box_style_option, None) check_box_point = QPoint( option.rect.x() + option.rect.width() / 2 - check_box_rect.width() / 2, option.rect.y() + option.rect.height() / 2 - check_box_rect.height() / 2) return QRect(check_box_point, check_box_rect.size())