def updateTable(self): """Syncronizes self.variables with table widget""" self.ui.tableWidget.setRowCount(len(self.variables)) for i in range(len(self.variables)): var = self.variables[i] item = QTableWidgetItem() item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) item.setText(var.name) self.ui.tableWidget.setItem(i, 0, item) item = QTableWidgetItem() item.setText("{}".format(var.valueRef)) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.ui.tableWidget.setItem(i, 1, item) item = QTableWidgetItem() item.setText(var.variability) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.ui.tableWidget.setItem(i, 2, item) item = QTableWidgetItem() item.setText(var.causality) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.ui.tableWidget.setItem(i, 3, item) item = QTableWidgetItem() item.setText(var.initial) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.ui.tableWidget.setItem(i, 4, item) item = QTableWidgetItem() item.setText(var.typeID) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.ui.tableWidget.setItem(i, 5, item) item = QTableWidgetItem() item.setText("{}".format(var.startValue)) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.ui.tableWidget.setItem(i, 6, item) item = QTableWidgetItem() item.setText(var.unit) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.ui.tableWidget.setItem(i, 7, item) item = QTableWidgetItem() item.setText(var.description) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.ui.tableWidget.setItem(i, 8, item) self.ui.tableWidget.resizeColumnsToContents() self.ui.tableWidget.setAlternatingRowColors(True) f = QFontMetrics(self.ui.tableWidget.font()) self.ui.tableWidget.verticalHeader().setDefaultSectionSize( f.lineSpacing()) self.ui.tableWidget.setMinimumHeight(f.lineSpacing() * 8)
def paintEvent(self, event): super(DeviceCard, self).paintEvent(event) painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing, True) painter.setRenderHints(QPainter.SmoothPixmapTransform) path = QPainterPath() # 绘制图标 c = 0 r = 0 margin = 0 if not self.hover_progress or self.hover_progress < 20: c = self.choking r = self.radius_x else: c = self.choking * (1 - self.getNolinearProg( self.hover_progress, NolinearType.SlowFaster if self.hovering else NolinearType.SlowFaster)) r = self.radius_x if self.radius_zoom < 0 else self.radius_x + ( self.radius_zoom - self.radius_x) * self.hover_progress / 100 rect = QRectF(10, 10, 80 - c * 2, 80 - c * 2) path.addRoundedRect(rect, 4, 4) painter.save() painter.setClipPath(path, Qt.IntersectClip) painter.drawPixmap(rect.x(), rect.y(), rect.width(), rect.height(), self.model.icon) painter.restore() # 绘制编号 fm = QFontMetrics(self.title_font) line_height = fm.lineSpacing() painter.setPen(self.title_color) painter.setFont(self.title_font) painter.drawText(QPoint(94 - c * 2, 36), self.model.sn) fm = QFontMetrics(self.body_font) line_height = fm.lineSpacing() painter.setPen(self.body_color) painter.setFont(self.body_font) f_rect = fm.boundingRect(QRect(94 - c * 2, 30 + line_height, 0, 0), Qt.TextSingleLine, self.model.name) painter.drawText(f_rect, Qt.TextSingleLine, self.model.name) f_rect = fm.boundingRect(QRect(94 - c * 2, 46 + line_height, 0, 0), Qt.TextSingleLine, self.model.active) painter.drawText(f_rect, Qt.TextSingleLine, self.model.active) # 状态位置 self.tag.move(220 - self.tag.tag_width() - 10 - c, 10)
def setCameraInformation(self, cameraInfo): """Take the camera information, format and display it. Parameters ---------- cameraInfo : OrderedDict The set of camera information to display. """ lines = [] max_width = 0 max_height = len(cameraInfo.keys()) for key, value in cameraInfo.items(): lines.append(f'<p><b>{key}</b>: {value}</p>') max_width = max(max_width, len(key) + len(str(value)) + 2) fontMetrics = QFontMetrics(self.cameraInfoTextBrowser.font()) scale_factor = 1.75 browser_height = int(max_height * fontMetrics.lineSpacing() * scale_factor) browser_width = max_width * fontMetrics.averageCharWidth() self.cameraInfoTextBrowser.setHtml(os.linesep.join(lines)) if self.cameraInfoTextBrowser.minimumHeight() < browser_height: self.cameraInfoTextBrowser.setMinimumHeight(browser_height) self.cameraInfoTextBrowser.setMaximumHeight(browser_height) if self.cameraInfoTextBrowser.minimumWidth() < browser_width: self.cameraInfoTextBrowser.setMinimumWidth(browser_width) self.cameraInfoTextBrowser.setMaximumWidth(browser_width)
def __config_control(self): # self.__combo_uri.setEditable(True) self.__combo_index_sel.setVisible(False) self.__check_identity_enable.setChecked(True) self.__check_datetime_enable.setChecked(True) self.__datetime_since.setDateTime(default_since()) self.__datetime_until.setDateTime(now()) self.__button_select.clicked.connect(self.on_button_reset) self.__button_select.clicked.connect(self.on_button_select) self.__button_query.clicked.connect(self.on_button_query) self.__button_export.clicked.connect(self.on_button_export) self.__button_clear.clicked.connect(self.on_button_clear) for _id, name in SUPPORT_INDEX.items(): self.__combo_index_sel.addItem('%s | %s' % (_id, name)) if self.__context is not None: data_agents = self.__context.get_sas_interface().sas_get_data_agent_probs() all_uri = [da.get('uri', '') for da in data_agents] for uri in all_uri: self.__combo_uri.addItem(uri) self.__combo_uri.currentIndexChanged.connect(self.on_uri_selection_changed) font = self.__text_selected.font() font_m = QFontMetrics(font) text_height = font_m.lineSpacing() self.__text_selected.setFixedHeight(3 * text_height) self.__text_selected.setEnabled(False) self.__update_selection_text() self.setMinimumSize(QSize(800, 600)) self.setWindowTitle('Data Browser')
def __init__(self, parent=None): super(QMainWindow,self).__init__() #--------------------------------------------------------------- statusWin = QLabel(self) #statusWin = QPlainTextEdit(self) # status window #statusWin.appendHtml("<b>hallo<br>hallo2<br>hallo3</b>") tabWin = TabWidgets(self) # tabbed window print('hint status win: {0}'.format(statusWin.sizeHint())) print('hint_tab win: {0}'.format(tabWin.sizeHint())) print('hint main win: {0}'.format(self.sizeHint())) mSize = QFontMetrics(statusWin.font()) rowHt = mSize.lineSpacing() # fixed height for statusWin needed as the sizeHint of tabWin is very small #statusWin.setFixedHeight(4*rowHt+4) # add status window underneath plot Tab Widgets: spltVMain = QSplitter(QtCore.Qt.Vertical) spltVMain.addWidget(tabWin) spltVMain.addWidget(statusWin) # relative initial sizes of subwidgets, this doesn't work here # spltVMain.setStretchFactor(4,1) spltVMain.setSizes([statusWin.sizeHint().height()*2, statusWin.sizeHint().height()*0.05]) spltVMain.setFocus() # make spltVMain occupy the main area of QMainWindow and set inheritance self.setCentralWidget(spltVMain) print('size tabs: {0}'.format(tabWin.size())) print('size status: {0}'.format(statusWin.size())) print('size self: {0}'.format(self.size()))
def updateRects_v2(self, option, index): margin = self.margin * 2 iconSize = max(24 * self.factor, 18) item = index.internalPointer() fm = QFontMetrics(option.font) h = fm.lineSpacing() self.itemRect = option.rect.adjusted(margin, margin, -margin, -margin) top = 15 * self.factor self.topRect = QRect(self.itemRect) self.topRect.setHeight(top) self.cardRect = QRect(self.itemRect.topLeft() + QPoint(0, top), self.itemRect.bottomRight()) self.iconRect = QRect(self.cardRect.topLeft() + QPoint(margin, margin), QSize(iconSize, iconSize)) self.labelRect = QRect(self.cardRect.topRight() - QPoint(margin + self.factor * 18, 1), self.cardRect.topRight() + QPoint(- margin - self.factor * 4, self.factor * 24)) self.titleRect = QRect(self.iconRect.topRight() + QPoint(margin, 0), self.labelRect.bottomLeft() - QPoint(margin, margin)) self.titleRect.setBottom(self.iconRect.bottom()) self.mainRect = QRect(self.iconRect.bottomLeft() + QPoint(0, margin), self.cardRect.bottomRight() - QPoint(margin, 2*margin)) self.mainRect.setLeft(self.titleRect.left()) self.mainLineRect = QRect(self.mainRect.topLeft(), self.mainRect.topRight() + QPoint(0, h)) self.mainTextRect = QRect(self.mainLineRect.bottomLeft() + QPoint(0, margin), self.mainRect.bottomRight()) if not item.data(Outline.summarySentence): self.mainTextRect.setTopLeft(self.mainLineRect.topLeft())
def __init__(self, chat_window, nick, parent=None): QWidget.__init__(self, parent) self.chat_window = chat_window self.nick = nick self.disabled = False self.cleared = False self.url_regex = re.compile(URL_REGEX) self.chat_log = QTextBrowser() self.chat_log.setOpenExternalLinks(True) self.chat_input = QTextEdit() self.chat_input.textChanged.connect(self.chatInputTextChanged) self.send_button = QPushButton("Send") self.send_button.clicked.connect(self.sendMessage) # Set the min height for the chatlog and a matching fixed height for the send button chat_input_font_metrics = QFontMetrics(self.chat_input.font()) self.chat_input.setMinimumHeight(chat_input_font_metrics.lineSpacing() * 3) self.send_button.setFixedHeight(chat_input_font_metrics.lineSpacing() * 3) hbox = QHBoxLayout() hbox.addWidget(self.chat_input) hbox.addWidget(self.send_button) # Put the chatinput and send button in a wrapper widget so they may be added to the splitter chat_input_wrapper = QWidget() chat_input_wrapper.setLayout(hbox) chat_input_wrapper.setMinimumHeight(chat_input_font_metrics.lineSpacing() * 3.7) # Put the chat log and chat input into a splitter so the user can resize them at will splitter = QSplitter(Qt.Vertical) splitter.addWidget(self.chat_log) splitter.addWidget(chat_input_wrapper) splitter.setSizes([int(parent.height()), 1]) hbox = QHBoxLayout() hbox.addWidget(splitter) self.setLayout(hbox) self.typing_timer = QTimer() self.typing_timer.setSingleShot(True) self.typing_timer.timeout.connect(self.stoppedTyping)
def __init__(self, control_window: Union[ControlWindow, None] = None): """Constructor.""" QTextEdit.__init__(self, parent=control_window) self.control_window = control_window metrics = QFontMetrics(self.font()) line_height = metrics.lineSpacing() + 1 self.setFixedHeight(line_height)
def __init__(self, tab): QWidget.__init__(self, tab) self._tab = tab self.chat_browser = QTextBrowser() self.chat_browser.setOpenExternalLinks(True) self.chat_input = QTextEdit() self.chat_input.installEventFilter(self) self.chat_input.textChanged.connect(self.send_typing_message) self.typing_stamp = -1 self.send_button = QPushButton('Send') self.send_button.clicked.connect(self.send_message) self.invite_button = QPushButton('Invite') self.invite_button.clicked.connect(self.goto_invite) font_metrics = QFontMetrics(self.chat_input.font()) self.chat_input.setMinimumHeight(font_metrics.lineSpacing() * 3) self.send_button.setFixedHeight(font_metrics.lineSpacing() * 2) self.invite_button.setFixedHeight(font_metrics.lineSpacing() * 2) hbox = QHBoxLayout() hbox.addWidget(self.chat_input) vbox = QVBoxLayout() vbox.addStretch(1) vbox.addWidget(self.send_button) vbox.addStretch(1) vbox.addWidget(self.invite_button) vbox.addStretch(1) hbox.addLayout(vbox) input_wrapper = QWidget() input_wrapper.setLayout(hbox) input_wrapper.setMinimumHeight(font_metrics.lineSpacing() * 3.7) splitter = QSplitter(Qt.Vertical) splitter.addWidget(self.chat_browser) splitter.addWidget(input_wrapper) splitter.setSizes([int(self.parent().height()), 1]) hbox = QHBoxLayout() hbox.addWidget(splitter) self.setLayout(hbox)
def message_resize(self): height = self.send_input.document().documentLayout().documentSize( ).height() fm = QFontMetrics(variables.font) space = self.send_input.document().documentMargin() rowNum = int( (height - (2 * self.send_input.document().documentMargin())) / fm.lineSpacing()) if rowNum == 0: rowNum = 1 if rowNum > variables.MAX_ROWS: rowNum = variables.MAX_ROWS margins = self.send_input.contentsMargins() height = fm.lineSpacing() * rowNum + ( self.send_input.document().documentMargin() + self.send_input. frameWidth()) * 2 + margins.top() + margins.bottom() self.send_input.setFixedHeight(int(height))
def setModel(self, model): self.horizontalHeader().set_filter_boxes(model.columnCount()) self._proxy_model.setSourceModel(model) self._proxy_model.sort(0, Qt.AscendingOrder) super().setModel(self._proxy_model) font = model.data(0, Qt.FontRole) if font is None: font = self.font() metrics = QFontMetrics(font) self.verticalHeader().setDefaultSectionSize(metrics.lineSpacing() * 1.5) self.horizontalHeader().setDefaultSectionSize(metrics.maxWidth() * 5)
def _init_comment(self): self._comment_box = QPlainTextEdit() metrics = QFontMetrics(self._comment_box.font()) row_height = metrics.lineSpacing() # four rows self._comment_box.setFixedHeight(4 * row_height) self._general_layout.addWidget(QLabel("Comment:")) self._general_layout.addWidget(self._comment_box)
def __init__(self, parent, layerList): QDialog.__init__(self, parent) self.setWindowTitle('Open Vector Layer') self.layerList = layerList self.layerTypeButtonGroup = QButtonGroup() # enforces exclusivity self.layerNameRadio = QRadioButton("Layer Name") self.layerSQLRadio = QRadioButton("SQL") self.layerTypeButtonGroup.addButton(self.layerNameRadio) self.layerTypeButtonGroup.addButton(self.layerSQLRadio) self.layerNameRadio.setChecked(True) # the default self.mainLayout = QVBoxLayout() self.nameLayout = QHBoxLayout() self.nameLayout.addWidget(self.layerNameRadio) self.nameCombo = QComboBox() for layerName in layerList: self.nameCombo.addItem(layerName) self.nameLayout.addWidget(self.nameCombo) self.mainLayout.addLayout(self.nameLayout) self.sqlLayout = QHBoxLayout() self.sqlLayout.addWidget(self.layerSQLRadio) self.sqlText = QTextEdit() self.sqlText.setReadOnly(True) fm = QFontMetrics(self.sqlText.font()) self.sqlText.setFixedHeight(NUM_SQL_ROWS * fm.lineSpacing()) self.layerNameRadio.toggled.connect(self.typeToggled) self.sqlLayout.addWidget(self.sqlText) self.mainLayout.addLayout(self.sqlLayout) # ok and cancel buttons self.okButton = QPushButton(self) self.okButton.setText("OK") self.okButton.setDefault(True) self.okButton.clicked.connect(self.accept) self.cancelButton = QPushButton(self) self.cancelButton.setText("Cancel") self.cancelButton.clicked.connect(self.reject) self.buttonLayout = QHBoxLayout() self.buttonLayout.addWidget(self.okButton) self.buttonLayout.addWidget(self.cancelButton) self.mainLayout.addLayout(self.buttonLayout) self.setLayout(self.mainLayout)
def __init__(self, dialog, *__args): super().__init__(*__args) self.dialog = dialog self.setStyleSheet('padding: 0; padding: 0 5px;') bar = QScrollBar() bar.setFixedHeight(0) bar.setFixedWidth(0) font_metric = QFontMetrics(self.font()) row_height = font_metric.lineSpacing() self.setFixedHeight(row_height + 10) # 10 == 2*5px padding self.setMinimumWidth(400)
def defaultTextGeometry(self, point): """ Return the default text geometry. Used in case the user single clicked in the scene. """ font = self.annotation_item.font() metrics = QFontMetrics(font) spacing = metrics.lineSpacing() margin = self.annotation_item.document().documentMargin() rect = QRectF(QPointF(point.x(), point.y() - spacing - margin), QSizeF(150, spacing + 2 * margin)) return rect
def __init__(self, win): from .main_window import ElectrumWindow assert isinstance(win, ElectrumWindow) and win.amount_e and win.wallet ScanQRTextEdit.__init__(self) self.win = win self.amount_edit = win.amount_e document = self.document() document.contentsChanged.connect(self.update_size) fontMetrics = QFontMetrics(document.defaultFont()) self.fontSpacing = fontMetrics.lineSpacing() margins = self.contentsMargins() self.verticalMargins = margins.top() + margins.bottom() self.verticalMargins += self.frameWidth() * 2 self.verticalMargins += int(document.documentMargin() * 2) self.heightMin = self.fontSpacing + self.verticalMargins self.heightMax = (self.fontSpacing * 10) + self.verticalMargins self.c = None self.textChanged.connect(self.check_text) self.outputs = [] self.errors = [] self.is_pr = False self.is_alias = self.validated = False self.scan_f = win.pay_to_URI self.update_size() self.payto_address = None self._ca_busy = False self._original_style_sheet = self.styleSheet() or '' self.previous_payto = '' self.preivous_ca_could_not_verify = set() if sys.platform in ('darwin', ): # See issue #1411 -- on *some* macOS systems, clearing the # payto field with setText('') ends up leaving "ghost" pixels # in the field, which look like the text that was just there. # This situation corrects itself eventually if another repaint # is issued to the widget. I couldn't figure out why it is happening # and the workaround is simply to force a repaint using this trick # for all textChanged events. -Calin self.textChanged.connect(self.repaint) self.verticalScrollBar().valueChanged.connect( self._vertical_scroll_bar_changed)
def mousePressEvent(self, event): if self.foldArea > 0: xofs = self.width() - self.foldArea font_metrics = QFontMetrics(self.edit.document().defaultFont()) fh = font_metrics.lineSpacing() ys = event.localPos().y() lineNumber = 0 if event.pos().x() > xofs: pattern = self.pat if self.edit.lang != "python": pattern = self.patNotPython block = self.edit.firstVisibleBlock() viewport_offset = self.edit.contentOffset() page_bottom = self.edit.viewport().height() while block.isValid(): position = self.edit.blockBoundingGeometry( block).topLeft() + viewport_offset if position.y() > page_bottom: break if position.y() < ys and (position.y() + fh) > ys and \ pattern.match(str(block.text())): lineNumber = block.blockNumber() + 1 break elif position.y() < ys and (position.y() + fh) > ys and \ event.button() == Qt.LeftButton: line = block.blockNumber() if line in self._breakpoints: self._breakpoints.remove(line) else: self._breakpoints.append(line) self.update() break elif position.y() < ys and (position.y() + fh) > ys and \ event.button() == Qt.RightButton: line = block.blockNumber() if line in self._bookmarks: self._bookmarks.remove(line) else: self._bookmarks.append(line) self.update() break block = block.next()# block = next(block) self._save_breakpoints_bookmarks() if lineNumber > 0: self.code_folding_event(lineNumber)
def mousePressEvent(self, event): if self.foldArea > 0: xofs = self.width() - self.foldArea font_metrics = QFontMetrics(self.edit.document().defaultFont()) fh = font_metrics.lineSpacing() ys = event.posF().y() lineNumber = 0 if event.pos().x() > xofs: pattern = self.pat if self.edit.lang != "python": pattern = self.patNotPython block = self.edit.firstVisibleBlock() viewport_offset = self.edit.contentOffset() page_bottom = self.edit.viewport().height() while block.isValid(): position = self.edit.blockBoundingGeometry( block).topLeft() + viewport_offset if position.y() > page_bottom: break if (position.y() < ys and (position.y() + fh) > ys and pattern.match(str(block.text()))): if not block.blockNumber() in self._endDocstringBlocks: lineNumber = block.blockNumber() + 1 break if (position.y() < ys and (position.y() + fh) > ys and event.button() == Qt.LeftButton): line = block.blockNumber() self.set_breakpoint(line) break elif (position.y() < ys and (position.y() + fh) > ys and event.button() == Qt.RightButton): line = block.blockNumber() self.set_bookmark(line) break block = block.next() if lineNumber > 0: self.code_folding_event(lineNumber)
def __init__(self, send_tab: 'SendTab'): CompletionTextEdit.__init__(self) ScanQRTextEdit.__init__(self, config=send_tab.config, setText=self._on_input_btn) Logger.__init__(self) self.send_tab = send_tab self.win = send_tab.window self.app = QApplication.instance() self.amount_edit = self.send_tab.amount_e self.setFont(QFont(MONOSPACE_FONT)) document = self.document() document.contentsChanged.connect(self.update_size) fontMetrics = QFontMetrics(document.defaultFont()) self.fontSpacing = fontMetrics.lineSpacing() margins = self.contentsMargins() documentMargin = document.documentMargin() self.verticalMargins = margins.top() + margins.bottom() self.verticalMargins += self.frameWidth() * 2 self.verticalMargins += documentMargin * 2 self.heightMin = self.fontSpacing + self.verticalMargins self.heightMax = (self.fontSpacing * 10) + self.verticalMargins self.c = None self.addPasteButton(setText=self._on_input_btn) self.textChanged.connect(self._on_text_changed) self.outputs = [] # type: List[PartialTxOutput] self.errors = [] # type: List[PayToLineError] self.disable_checks = False self.is_alias = False self.update_size() self.payto_scriptpubkey = None # type: Optional[bytes] self.lightning_invoice = None self.previous_payto = ''
def updateRects_v2(self, option, index): margin = self.margin * 2 iconSize = max(24 * self.factor, 18) item = index.internalPointer() fm = QFontMetrics(option.font) h = fm.lineSpacing() self.itemRect = option.rect.adjusted(margin, margin, -margin, -margin) top = 15 * self.factor self.topRect = QRect(self.itemRect) self.topRect.setHeight(top) self.cardRect = QRect(self.itemRect.topLeft() + QPoint(0, top), self.itemRect.bottomRight()) self.iconRect = QRect(self.cardRect.topLeft() + QPoint(margin, margin), QSize(iconSize, iconSize)) self.labelRect = QRect( self.cardRect.topRight() - QPoint(margin + self.factor * 18, 1), self.cardRect.topRight() + QPoint(-margin - self.factor * 4, self.factor * 24)) self.titleRect = QRect( self.iconRect.topRight() + QPoint(margin, 0), self.labelRect.bottomLeft() - QPoint(margin, margin)) self.titleRect.setBottom(self.iconRect.bottom()) self.mainRect = QRect( self.iconRect.bottomLeft() + QPoint(0, margin), self.cardRect.bottomRight() - QPoint(margin, 2 * margin)) self.mainRect.setLeft(self.titleRect.left()) self.mainLineRect = QRect(self.mainRect.topLeft(), self.mainRect.topRight() + QPoint(0, h)) self.mainTextRect = QRect( self.mainLineRect.bottomLeft() + QPoint(0, margin), self.mainRect.bottomRight()) if not item.data(Outline.summarySentence): self.mainTextRect.setTopLeft(self.mainLineRect.topLeft())
def __init__(self, *args): QTextEdit.__init__(self) # Set text to be monospace doc = self.document() font = doc.defaultFont() font.setFamily("Courier New") doc.setDefaultFont(font) # Set the background color to green palette = self.palette() palette.setColor(self.backgroundRole(), QColor(200, 255, 200)) self.setPalette(palette) self.setAutoFillBackground(True) # Set the height of the box # 10 Lines tall nRows = 10 doc = self.document() fm = QFontMetrics(doc.defaultFont()) margins = self.contentsMargins() height = fm.lineSpacing() * nRows + 2 * (doc.documentMargin( ) + self.frameWidth()) + margins.top() + margins.bottom() self.setFixedHeight(height)
def paint(self, painter, option, index): if (index.isValid() == False): return painter.save() painter.setOpacity(0.6) if (option.state & QStyle.State_Selected): painter.fillRect(option.rect, option.palette.highlight()) if (option.state & QStyle.State_MouseOver): painter.setOpacity(0.25) painter.fillRect(option.rect, option.palette.highlight()) painter.setOpacity(1.0) painter.setFont(option.font) metrics = QFontMetrics(option.font) regular = QFont(option.font) italics = QFont(option.font) italics.setItalic(True) icon = QIcon(index.data(CPE.IMAGE)) rect = option.rect margin = 4 decoratonSize = QSize(option.decorationSize) imageSize = icon.actualSize(option.decorationSize) leftSideThumbnail = (decoratonSize.width() - imageSize.width()) / 2 if (rect.width() < decoratonSize.width()): leftSideThumbnail = max(0, (rect.width() - imageSize.width()) / 2) topSizeThumbnail = ( (rect.height() - imageSize.height()) / 2) + rect.top() painter.drawImage( QRect(leftSideThumbnail, topSizeThumbnail, imageSize.width(), imageSize.height()), icon.pixmap(imageSize).toImage()) labelWidth = rect.width() - decoratonSize.width() - (margin * 3) if (decoratonSize.width() + (margin * 2) < rect.width()): textRect = QRect(decoratonSize.width() + margin, margin + rect.top(), labelWidth, metrics.height()) textTitle = metrics.elidedText( str(index.row() + 1) + ". " + index.data(CPE.TITLE), Qt.ElideRight, labelWidth) painter.drawText(textRect, Qt.TextWordWrap, textTitle) if rect.height() / (metrics.lineSpacing() + margin) > 5 or index.data( CPE.KEYWORDS) is not None: painter.setOpacity(0.6) textRect = QRect(textRect.left(), textRect.bottom() + margin, labelWidth, metrics.height()) if textRect.bottom() < rect.bottom(): textKeyWords = index.data(CPE.KEYWORDS) if textKeyWords == None: textKeyWords = i18n("No keywords") painter.setOpacity(0.3) painter.setFont(italics) textKeyWords = metrics.elidedText(textKeyWords, Qt.ElideRight, labelWidth) painter.drawText(textRect, Qt.TextWordWrap, textKeyWords) painter.setFont(regular) if rect.height() / (metrics.lineSpacing() + margin) > 3: painter.setOpacity(0.6) textRect = QRect(textRect.left(), textRect.bottom() + margin, labelWidth, metrics.height()) if textRect.bottom() + metrics.height() < rect.bottom(): textLastEdit = index.data(CPE.LASTEDIT) if textLastEdit is None: textLastEdit = i18n("No last edit timestamp") if index.data(CPE.EDITOR) is not None: textLastEdit += " - " + index.data(CPE.EDITOR) if (index.data(CPE.LASTEDIT) is None) and (index.data( CPE.EDITOR) is None): painter.setOpacity(0.3) painter.setFont(italics) textLastEdit = metrics.elidedText(textLastEdit, Qt.ElideRight, labelWidth) painter.drawText(textRect, Qt.TextWordWrap, textLastEdit) painter.setFont(regular) descRect = QRect(textRect.left(), textRect.bottom() + margin, labelWidth, (rect.bottom() - margin) - (textRect.bottom() + margin)) if textRect.bottom() + metrics.height() < rect.bottom(): textRect.setBottom(textRect.bottom() + (margin / 2)) textRect.setLeft(textRect.left() - (margin / 2)) painter.setOpacity(0.4) painter.drawLine(textRect.bottomLeft(), textRect.bottomRight()) painter.setOpacity(1.0) textDescription = index.data(CPE.DESCRIPTION) if textDescription is None: textDescription = i18n("No description") painter.setOpacity(0.3) painter.setFont(italics) linesTotal = floor(descRect.height() / metrics.lineSpacing()) if linesTotal == 1: textDescription = metrics.elidedText( textDescription, Qt.ElideRight, labelWidth) painter.drawText(descRect, Qt.TextWordWrap, textDescription) else: descRect.setHeight(linesTotal * metrics.lineSpacing()) totalDescHeight = metrics.boundingRect( descRect, Qt.TextWordWrap, textDescription).height() if totalDescHeight > descRect.height(): if totalDescHeight - metrics.lineSpacing( ) > descRect.height(): painter.setOpacity(0.5) painter.drawText(descRect, Qt.TextWordWrap, textDescription) descRect.setHeight( (linesTotal - 1) * metrics.lineSpacing()) painter.drawText(descRect, Qt.TextWordWrap, textDescription) descRect.setHeight( (linesTotal - 2) * metrics.lineSpacing()) painter.drawText(descRect, Qt.TextWordWrap, textDescription) else: painter.setOpacity(0.75) painter.drawText(descRect, Qt.TextWordWrap, textDescription) descRect.setHeight( (linesTotal - 1) * metrics.lineSpacing()) painter.drawText(descRect, Qt.TextWordWrap, textDescription) else: painter.drawText(descRect, Qt.TextWordWrap, textDescription) painter.setFont(regular) painter.restore()
class KhtTextEdit(QPlainTextEdit): """ Widget which handle all specifities of implemented in the editor""" show_progress = pyqtSignal(bool) def __init__(self, parent=None, filename=None): """Initialization, can accept a filepath as argument""" QPlainTextEdit.__init__(self, parent) # Errors self.errors = {} self.isMAEMO = False self.scroller = None palette = self.palette() palette.setColor(QPalette.Base, Qt.white) palette.setColor(QPalette.Text, Qt.black) self.setPalette(palette) self.setWindowOpacity(0.9) self.hl_color = QColor('lightblue').lighter(120) self.qt18720 = False has_parent_settings = hasattr(parent, 'settings') if has_parent_settings and parent.settings.value("qt18720")== '2': self.qt18720 = True else: self.qt18720 = False # Brace matching self.bracepos = None # Init scroller and area which are tricky hack to speed scrolling # try: # scroller = self.property("kineticScroller") # scroller.setEnabled(True) # except: # print 'Cannot instance kineticScroller' #Plugin init moved to editor_window.py #initialization init of plugin system #Maybe be not the best place to do it ... #init_plugin_system({'plugin_path': '/home/opt/khteditor/plugins', # 'plugins': ['autoindent']}) #If we have a filename self.filename = filename if (self.filename == None) or (self.filename == ''): self.filename = u'Unnamed.txt' self.document().setModified(False) parent.setWindowTitle(self.filename) #Set no wrap if has_parent_settings and bool(parent.settings.value("WrapLine")): self.setLineWrapMode(QPlainTextEdit.NoWrap) else: self.setLineWrapMode(QPlainTextEdit.WidgetWidth) font = QFont() try: if parent.settings.contains('FontName'): font.setFamily(parent.settings.value('FontName')) else: font.setFamily("Courier") except: font.setFamily("Courier") #Get Font Size try: if parent.settings.contains('FontSize'): font.setPointSize(int(parent.settings.value('FontSize'))) else: font.setPointSize(11) except: font.setPointSize(11) #Set Font self.fmetrics = QFontMetrics(font) self.document().setDefaultFont(font) #Remove auto capitalization self.setInputMethodHints(Qt.ImhNoAutoUppercase) #Keep threaded plugins references to avoid them to be garbage collected self.threaded_plugins = [] self.enabled_plugins = getattr(parent, 'enabled_plugins', []) #Current Line highlight and Bracket matcher self.cursorPositionChanged.connect(self.curPositionChanged) self.textChanged.connect(self.textEditChanged) # Brackets ExtraSelection ... def detectLanguage(self,filename): for extension,lang in LANGUAGES: if filename.endswith(extension.lower()): return lang return None def loadHighlighter(self,filename=None): if not filename: filename = self.filename language = self.detectLanguage(filename) #Return None if language not yet implemented natively in KhtEditor if language == 'python': self.show_progress.emit(True) QApplication.processEvents() from .syntax.python_highlighter import Highlighter self.highlighter = Highlighter(self.document()) QApplication.processEvents() self.show_progress.emit(False) elif (language != None) and (language != 'None'): self.show_progress.emit(True) QApplication.processEvents() from .syntax.generic_highlighter import Highlighter self.highlighter = Highlighter(self.document(),language) QApplication.processEvents() self.show_progress.emit(False) else: self.show_progress.emit(True) QApplication.processEvents() from .syntax import pygments_highlighter self.highlighter = \ pygments_highlighter.Highlighter(self.document(), unicode(filename)) QApplication.processEvents() self.show_progress.emit(False) def textEditChanged(self): if self.scroller: #Resize doc = self.document() s = doc.size().toSize() s.setHeight((s.height() + 1) * (self.fmetrics.lineSpacing()+1) ) fr = self.frameRect() cr = self.contentsRect() self.setMinimumHeight(max(70, s.height() + (fr.height() - cr.height() - 1))) self.setMinimumWidth(max(240,s.width() + (fr.width()-cr.width()) - 1)) # Remove ensureVisible Hack which is now fixed in qt 4.7.2 # def ensureVisible(self,pos,xmargin,ymargin): # # visible = self.area.viewport().size() # currentPos = QPoint(self.area.horizontalScrollBar().value(), # self.area.verticalScrollBar().value()) # posRect = QRect(pos.x()-xmargin, pos.y()-ymargin,2*xmargin,2*ymargin) # visibleRect = QRect(currentPos, visible) # # if (visibleRect.contains(posRect)): # return # # newPos = currentPos # if (posRect.top() < visibleRect.top()): # newPos.setY(posRect.top()) # elif (posRect.bottom() > visibleRect.bottom()): # newPos.setY(posRect.bottom() - visible.height()) # if (posRect.left() < visibleRect.left()): # newPos.setX(posRect.left()) # elif (posRect.right() > visibleRect.right()): # newPos.setX(posRect.right() - visible.width()) # self.scroller.scrollTo(newPos) def curPositionChanged(self): #Plugin hook for plugin in filter_plugins_by_capability('beforeCursorPositionChanged',self.enabled_plugins): plugin.do_beforeCursorPositionChanged(self) #Hilight current line #Workarround QTBUG-18720 self.highlightCurrentLine() #Make sure cursor is visible #self.ensureCursorVisible() cursor = self.cursorRect() pos = cursor.center() #self.ensureVisible(pos.x(),pos.y(), 2*cursor.width()+20, 2*cursor.height()) if self.scroller: self.scroller.ensureVisible(pos.x(),pos.y(),2*cursor.width()+20, 2*cursor.height()) def match_left(self, block, character, start, found): map = {'{': '}', '(': ')', '[': ']'} block_jump = 0 while block.isValid() and (block_jump < 20): data = block.userData() if data is not None: braces = data.braces N = len(braces) for k in range(start, N): if braces[k].character == character: found += 1 if braces[k].character == map[character]: if not found: return braces[k].position + block.position() else: found -= 1 block = block.next() block_jump += 1 start = 0 def match_right(self, block, character, start, found): map = {'}': '{', ')': '(', ']': '['} block_jump = 0 while block.isValid() and (block_jump < 20): data = block.userData() if data is not None: braces = data.braces if start is None: start = len(braces) for k in range(start - 1, -1, -1): if braces[k].character == character: found += 1 if braces[k].character == map[character]: if found == 0: return braces[k].position + block.position() else: found -= 1 block = block.previous() block_jump += 1 start = None def check_brackets(self): left, right = QTextEdit.ExtraSelection(),\ QTextEdit.ExtraSelection() cursor = self.textCursor() block = cursor.block() data = block.userData() previous, next = None, None if data is not None: position = cursor.position() block_position = cursor.block().position() braces = data.braces N = len(braces) for k in range(0, N): if braces[k].position == position - block_position or\ braces[k].position == position - block_position - 1: previous = braces[k].position + block_position if braces[k].character in ['{', '(', '[']: next = self.match_left(block, braces[k].character, k + 1, 0) elif braces[k].character in ['}', ')', ']']: next = self.match_right(block, braces[k].character, k, 0) # if next is None: # next = -1 if (next is not None and next > 0) \ and (previous is not None and previous > 0): format = QTextCharFormat() cursor.setPosition(previous) cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor) format.setForeground(QColor('white')) format.setBackground(QColor('blue')) left.format = format left.cursor = cursor cursor.setPosition(next) cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor) format.setForeground(QColor('white')) format.setBackground(QColor('blue')) right.format = format right.cursor = cursor return left, right elif previous is not None: format = QTextCharFormat() cursor.setPosition(previous) cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor) format.setForeground(QColor('white')) format.setBackground(QColor('red')) left.format = format left.cursor = cursor return (left,) elif next is not None: format = QTextCharFormat() cursor.setPosition(next) cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor) format.setForeground(QColor('white')) format.setBackground(QColor('red')) left.format = format left.cursor = cursor return (left,) #PySide Bug : The type of e is QEvent instead of QKeyEvent def keyPressEvent(self, event): """Intercept the key event to lets plugin do something if they want""" if event.type() == QEvent.KeyPress: for plugin in filter_plugins_by_capability('beforeKeyPressEvent',self.enabled_plugins): plugin.do_beforeKeyPressEvent(self,event) QPlainTextEdit.keyPressEvent(self, event) for plugin in filter_plugins_by_capability('afterKeyPressEvent',self.enabled_plugins): plugin.do_afterKeyPressEvent(self,event) def closeEvent(self,event): """Catch the close event and ask to save if document is modified""" answer = self.document().isModified() and \ QMessageBox.question(self, "Text Editor - Unsaved Changes", "Save unsaved changes in %s?" % self.filename, QMessageBox.Yes| QMessageBox.No| QMessageBox.Close) if answer == QMessageBox.Yes: try: self.save() event.accept() except (IOError, OSError) as ioError: QMessageBox.warning(self, "Text Editor -- Save Error", "Failed to save %s: %s" % (self.filename, ioError)) event.ignore() elif answer == QMessageBox.Close: return event.ignore() else: return event.accept() def save(self): """Hum ... just save ...""" if self.filename.startswith("Unnamed"): filename = self.parent().parent().parent().saveAsFile() if not (filename == ''): return self.filename = filename self.setWindowTitle( QFileInfo(self.filename).fileName()) exception = None filehandle = None try: #Before FileSave plugin hook for plugin in filter_plugins_by_capability('beforeFileSave',self.enabled_plugins): plugin.do_beforeFileSave(self) filehandle = QFile(self.filename) if not filehandle.open( QIODevice.WriteOnly): raise IOError(unicode(filehandle.errorString())) stream = QTextStream(filehandle) stream.setCodec("UTF-8") stream << self.toPlainText() self.document().setModified(False) RecentFiles().append(self.filename) except (IOError, OSError) as ioError: exception = ioError finally: if filehandle is not None: filehandle.close() for plugin in filter_plugins_by_capability('afterFileSave',self.enabled_plugins): plugin.do_afterFileSave(self) if exception is not None: raise exception def __find_brace_match(self, position, brace, forward): if forward: bracemap = {'(': ')', '[': ']', '{': '}'} text = self.get_text(position, 'eof') i_start_open = 1 i_start_close = 1 else: bracemap = {')': '(', ']': '[', '}': '{'} text = self.get_text('sob', position) i_start_open = len(text)-1 i_start_close = len(text)-1 while True: if forward: i_close = text.find(bracemap[brace], i_start_close) else: i_close = text.rfind(bracemap[brace], 0, i_start_close+1) if i_close > -1: if forward: i_start_close = i_close+1 i_open = text.find(brace, i_start_open, i_close) else: i_start_close = i_close-1 i_open = text.rfind(brace, i_close, i_start_open+1) if i_open > -1: if forward: i_start_open = i_open+1 else: i_start_open = i_open-1 else: # found matching brace if forward: return position+i_close else: return position-(len(text)-i_close) else: # no matching brace return def __highlight(self, positions, color=None, cancel=False): cursor = QTextCursor(self.document()) modified = self.document().isModified() for position in positions: if position > self.get_position('eof'): return cursor.setPosition(position) cursor.movePosition( QTextCursor.NextCharacter, QTextCursor.KeepAnchor) charformat = cursor.charFormat() pen = QPen(Qt.NoPen) if cancel else QPen(color) charformat.setTextOutline(pen) cursor.setCharFormat(charformat) if cancel: charformat = QTextCharFormat() cursor.movePosition( QTextCursor.NextCharacter, QTextCursor.KeepAnchor) cursor.setCharFormat(charformat) cursor.clearSelection() self.setCurrentCharFormat(charformat) self.document().setModified(modified) def highlightCurrentLine(self): #Hilgight background _selection = QTextEdit.ExtraSelection() _selection.cursor = self.textCursor() _selection.cursor.clearSelection() _selection.format.setBackground(self.hl_color) _selection.format.setProperty( QTextFormat.FullWidthSelection, True) extraSelection = [] extraSelection.append(_selection) extras = self.check_brackets() if extras: extraSelection.extend(extras) if not self.qt18720: self.setExtraSelections(extraSelection) def load(self): """Load ?""" exception = None filehandle = None try: filehandle = QFile(self.filename) if not filehandle.open( QIODevice.ReadOnly): raise IOError(unicode(filehandle.errorString())) stream = QTextStream(filehandle) stream.setCodec("UTF-8") QApplication.processEvents() self.setPlainText(stream.readAll()) self.document().setModified(False) self.setWindowTitle( QFileInfo(self.filename).fileName()) self.loadHighlighter(self.filename) for plugin in filter_plugins_by_capability('afterFileOpen',self.enabled_plugins): plugin.do_afterFileOpen(self) except (IOError, OSError) as error: exception = error finally: if filehandle is not None: filehandle.close() if exception is not None: raise exception def isModified(self): """Return True if the document is modified""" return self.document().isModified() def unindent(self): """UnIndent the current selection or line""" maincursor = self.textCursor() if not maincursor.hasSelection(): maincursor.movePosition( QTextCursor.StartOfBlock) line = str(self.document().findBlockByNumber(maincursor\ .blockNumber()).text()) whitespace = re.match(r"(\s{0,4})", line).group(1) for i in range(len(whitespace)): #@UnusedVariable maincursor.deleteChar() else: block = self.document().findBlock(maincursor.selectionStart()) while True: whitespace = re.match(r"(\s{0,4})", str(block.text())).group(1) cursor = self.textCursor() cursor.setPosition(block.position()) for i in range(len(whitespace)): #@UnusedVariable cursor.deleteChar() if block.contains(maincursor.selectionEnd()): break block = block.next() def indent(self): """Indent the current selection or line""" maincursor = self.textCursor() if not maincursor.hasSelection(): maincursor.movePosition( QTextCursor.StartOfBlock) maincursor.insertText(" ") else: block = self.document().findBlock(maincursor.selectionStart()) while True: cursor = self.textCursor() cursor.setPosition(block.position()) cursor.insertText(" ") if block.contains(maincursor.selectionEnd()): break block = block.next() def replace_all(self, what, new, *args): """Replace all occurence of a search arg[0] -> QTextDocument.FindCaseSensitively arg[1] -> QTextDocument.FindWholeWords arg[2] -> QTextDocument.FindBackward arg[3] -> QTextDocument.RegEx """ # Use flags for case match flags = QTextDocument.FindFlags() if args[0]: flags = flags| QTextDocument.FindCaseSensitively if args[1]: flags = flags| QTextDocument.FindWholeWords if args[2]: flags = flags| QTextDocument.FindBackward # Beginning of undo block pcursor = self.textCursor() pcursor.beginEditBlock() #cursor at start as we replace from start cursor = self.textCursor() cursor.setPosition(0) # Replace all we can while True: # self is the QTextEdit if args[3]: cursor=self.document().find( QRegExp(what), cursor,flags) else: cursor=self.document().find(what,cursor,flags) if not cursor.isNull(): if cursor.hasSelection(): cursor.insertText(new) else: print('no selection') else: break # Mark end of undo block pcursor.endEditBlock() def replace(self, what, new, *args): """Replace the first occurence of a search arg[0] -> QTextDocument.FindCaseSensitively arg[1] -> QTextDocument.FindWholeWords arg[2] -> QTextDocument.FindBackward arg[3] -> QTextDocument.RegEx """ # Use flags for case match flags = QTextDocument.FindFlags() if args[0]: flags = flags| QTextDocument.FindCaseSensitively if args[1]: flags = flags| QTextDocument.FindWholeWords if args[2]: flags = flags| QTextDocument.FindBackward # Beginning of undo block pcursor = self.textCursor() pcursor.beginEditBlock() cursor = self.textCursor() # Replace # self is the QTextEdit if args[3]==True: cursor = self.document().find( QRegExp(what), cursor, flags) else: cursor = self.document().find(what, cursor, flags) if not cursor.isNull(): if cursor.hasSelection(): cursor.insertText(new) # Mark end of undo block pcursor.endEditBlock() def find(self, what, *args): """Perform a search arg[0] -> QTextDocument.FindCaseSensitively arg[1] -> QTextDocument.FindWholeWords arg[2] -> QTextDocument.FindBackward arg[3] -> QTextDocument.RegEx """ print('find called: "%s" (%s)' % (what, args)) if not args: flags = QTextDocument.FindFlags() elif len(args) == 1 and type(args[0]) == QTextDocument.FindFlags: flags = args[0] else: flags = QTextDocument.FindFlags() # Use flags for case match if args[0]==True: flags = flags | QTextDocument.FindCaseSensitively if args[1]==True: flags = flags | QTextDocument.FindWholeWords if args[2]==True: flags = flags | QTextDocument.FindBackward cursor = self.textCursor() if len(args) >= 4 and args[3]==True: cursor = self.document().find(QRegExp(what), cursor , flags) else: cursor = self.document().find(what, cursor, flags) if not cursor.isNull(): self.setTextCursor(cursor) return not cursor.isNull() def duplicate(self): """Duplicate the current line or selection""" maincursor = self.textCursor() if not maincursor.hasSelection(): maincursor.movePosition( QTextCursor.StartOfBlock) line = str(self.document().\ findBlockByNumber(maincursor.blockNumber()).text()) maincursor.movePosition( QTextCursor.EndOfBlock) maincursor.insertText('\n'+line) else: block = self.document().findBlock(maincursor.selectionStart()) line = u'' while True: cursor = self.textCursor() cursor.setPosition(block.position()) line = line + '\n' + block.text() if block.contains(maincursor.selectionEnd()): break block = block.next() cursor.movePosition( QTextCursor.EndOfBlock) cursor.insertText(line) def gotoLine(self, line): print('goto line: %s' % line) cursor = self.textCursor() block = self.document().findBlockByLineNumber(line-1) cursor.setPosition(block.position()) self.setTextCursor(cursor) self.ensureCursorVisible() self.parent().activateWindow() def comment(self): """Comment the current line or selection""" maincursor = self.textCursor() if not maincursor.hasSelection(): maincursor.movePosition( QTextCursor.StartOfBlock) line = str(self.document().\ findBlockByNumber(maincursor.blockNumber()).text()) if line.startswith('#'): maincursor.deleteChar() else: maincursor.insertText("#") else: block = self.document().findBlock(maincursor.selectionStart()) while True: cursor = self.textCursor() cursor.setPosition(block.position()) if str(block.text()).startswith('#'): cursor.deleteChar() else: cursor.insertText("#") if block.contains(maincursor.selectionEnd()): break block = block.next() def __select_text(self, position_from, position_to): position_from = self.get_position(position_from) position_to = self.get_position(position_to) cursor = self.textCursor() cursor.setPosition(position_from) cursor.setPosition(position_to, QTextCursor.KeepAnchor) return cursor def get_position(self, position): cursor = self.textCursor() if position == 'cursor': pass elif position == 'sob': cursor.movePosition( QTextCursor.Start) elif position == 'sol': cursor.movePosition( QTextCursor.StartOfBlock) elif position == 'eol': cursor.movePosition( QTextCursor.EndOfBlock) elif position == 'eof': cursor.movePosition( QTextCursor.End) elif position == 'sof': cursor.movePosition( QTextCursor.Start) else: # Assuming that input argument was already a position return position return cursor.position() def get_text(self, position_from, position_to): """ Return text between *position_from* and *position_to* Positions may be positions or 'sob','sol', 'eol', 'sof', 'eof' or 'cursor' """ cursor = self.__select_text(position_from, position_to) text = cursor.selectedText() return unicode(text)
def setupUi(self) -> None: """ :return: """ # Generated Setup Code self.setObjectName("StockAnalysisTool_Ui") self.central_widget = QWidget(self) self.central_widget.setObjectName("central_widget") self.central_layout = QVBoxLayout(self.central_widget) self.central_layout.setObjectName("central_layout") self.title_label = QLabel(self.central_widget) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.title_label.sizePolicy().hasHeightForWidth()) self.title_label.setSizePolicy(sizePolicy) font = QFont() font.setFamily("Garamond") font.setPointSize(22) font.setBold(True) font.setWeight(75) self.title_label.setFont(font) self.title_label.setAlignment(Qt.AlignCenter) self.title_label.setObjectName("title_label") self.central_layout.addWidget(self.title_label) self.title_h_divider = QFrame(self.central_widget) self.title_h_divider.setFrameShape(QFrame.HLine) self.title_h_divider.setFrameShadow(QFrame.Sunken) self.title_h_divider.setObjectName("title_h_divider") self.central_layout.addWidget(self.title_h_divider) self.display_layout = QHBoxLayout() self.display_layout.setObjectName("display_layout") self.graph_layout = QVBoxLayout() self.graph_layout.setObjectName("graph_layout") self.date_axis = pg.DateAxisItem(orientation='bottom') self.graph = pg.PlotWidget(axisItems={'bottom': self.date_axis}) self.graph_legend = self.graph.addLegend() self.graph_layout.addWidget(self.graph) self.data_selection_layout = QGridLayout() self.open_data_cb = QCheckBox(self.central_widget) self.open_data_cb.setObjectName("open") self.data_selection_layout.addWidget(self.open_data_cb, 0, 0, 1, 1) self.high_data_cb = QCheckBox(self.central_widget) self.high_data_cb.setObjectName("high") self.data_selection_layout.addWidget(self.high_data_cb, 0, 1, 1, 1) self.low_data_cb = QCheckBox(self.central_widget) self.low_data_cb.setObjectName("low") self.data_selection_layout.addWidget(self.low_data_cb, 0, 2, 1, 1) self.close_data_cb = QCheckBox(self.central_widget) self.close_data_cb.setObjectName("close") self.data_selection_layout.addWidget(self.close_data_cb, 0, 3, 1, 1) self.adjclose_data_cb = QCheckBox(self.central_widget) self.adjclose_data_cb.setObjectName("adjclose") self.data_selection_layout.addWidget(self.adjclose_data_cb, 0, 4, 1, 1) self.volume_data_cb = QCheckBox(self.central_widget) self.volume_data_cb.setObjectName("volume") self.data_selection_layout.addWidget(self.volume_data_cb, 0, 5, 1, 1) self.graph_layout.addLayout(self.data_selection_layout) self.save_fig_btn = QPushButton(self.central_widget) self.save_fig_btn.setObjectName("save_fig_btn") self.graph_layout.addWidget(self.save_fig_btn) self.graph_options_layout = QGridLayout() self.sample_rate_label = QLabel(self.central_widget) self.sample_rate_label.setText("Sample Rate:") self.graph_options_layout.addWidget(self.sample_rate_label, 0, 0, 1, 1) self.sample_rate_combo = QComboBox(self.central_widget) self.sample_rate_combo.addItems(self.sample_rates) self.graph_options_layout.addWidget(self.sample_rate_combo, 0, 1, 1, 1) self.time_delta_label = QLabel(self.central_widget) self.time_delta_label.setText("Time delta:") self.graph_options_layout.addWidget(self.time_delta_label, 0, 2, 1, 1) self.time_delta_combo = QComboBox(self.central_widget) self.time_delta_combo.addItems(self.time_deltas) self.graph_options_layout.addWidget(self.time_delta_combo, 0, 3, 1, 1) self.graph_layout.addLayout(self.graph_options_layout) self.display_layout.addLayout(self.graph_layout) self.main_v_divider = QFrame(self.central_widget) self.main_v_divider.setFrameShape(QFrame.VLine) self.main_v_divider.setFrameShadow(QFrame.Sunken) self.main_v_divider.setObjectName("main_v_divider") self.display_layout.addWidget(self.main_v_divider) self.options_layout = QVBoxLayout() self.options_layout.setObjectName("options_layout") robinhood_account_layout = QHBoxLayout() robinhood_account_name_label = QLabel(self.central_widget) robinhood_account_name_label.setText("Robinhood Account:") self.robinhood_account_name_textedit = QTextEdit() robinhood_account_layout.addWidget(robinhood_account_name_label) robinhood_account_layout.addWidget( self.robinhood_account_name_textedit) self.options_layout.addLayout(robinhood_account_layout) robinhood_password_layout = QHBoxLayout() robinhood_account_password_label = QLabel(self.central_widget) robinhood_account_password_label.setText("Robinhood Password:"******"robinhood_login_button") self.options_layout.addWidget(self.robinhood_login_button) self.top_h_divider = QFrame(self.central_widget) self.top_h_divider.setFrameShape(QFrame.HLine) self.top_h_divider.setFrameShadow(QFrame.Sunken) self.top_h_divider.setObjectName("top_h_divider") self.options_layout.addWidget(self.top_h_divider) self.source_selection_layout = QHBoxLayout() self.source_selection_layout.setObjectName("source_selection_layout") self.source_label = QLabel(self.central_widget) self.source_label.setObjectName("source_label") self.source_selection_layout.addWidget(self.source_label) self.source_combo = QComboBox(self.central_widget) self.source_combo.setObjectName("source_combo") self.source_combo.addItem("") self.source_combo.addItem("") self.source_combo.addItem("") self.source_selection_layout.addWidget(self.source_combo) self.options_layout.addLayout(self.source_selection_layout) self.stock_selection_layout = QHBoxLayout() self.stock_selection_layout.setObjectName("stock_selection_layout") self.stock_label = QLabel(self.central_widget) self.stock_label.setObjectName("stock_label") self.stock_selection_layout.addWidget(self.stock_label) self.stock_combo = QComboBox(self.central_widget) self.stock_combo.setObjectName("stock_combo") self.stock_combo.addItems(self.valid_stock_tickers) self.stock_selection_layout.addWidget(self.stock_combo) self.options_layout.addLayout(self.stock_selection_layout) self.second_from_top_h_divider = QFrame(self.central_widget) self.second_from_top_h_divider.setFrameShape(QFrame.HLine) self.second_from_top_h_divider.setFrameShadow(QFrame.Sunken) self.second_from_top_h_divider.setObjectName( "second_from_top_h_divider") self.options_layout.addWidget(self.second_from_top_h_divider) self.momentum_indicator_label = QLabel(self.central_widget) self.momentum_indicator_label.setObjectName("momentum_indicator_label") self.options_layout.addWidget(self.momentum_indicator_label) # Momentum Indicators self.momentum_indicator_layout = QGridLayout() self.rsi_cb = QCheckBox(self.central_widget) self.rsi_cb.setObjectName("rsi_cb") self.momentum_indicator_layout.addWidget(self.rsi_cb, 0, 0, 1, 1) self.rsi_time_frame_label = QLabel(self.central_widget) self.rsi_time_frame_label.setText("Time frame:") self.momentum_indicator_layout.addWidget(self.rsi_time_frame_label, 0, 1, 1, 1) self.rsi_time_frame_text = QTextEdit(self.central_widget) font_metric = QFontMetrics(self.rsi_time_frame_text.font()) self.rsi_time_frame_text.setFixedHeight(font_metric.lineSpacing()) self.rsi_time_frame_text.setFixedWidth(50) self.rsi_time_frame_text.setText(str(self.rsi_n)) self.momentum_indicator_layout.addWidget(self.rsi_time_frame_text, 0, 2, 1, 1) self.williams_r_cb = QCheckBox(self.central_widget) self.williams_r_cb.setObjectName("williams_r_cb") self.momentum_indicator_layout.addWidget(self.williams_r_cb, 1, 0, 1, 1) self.cmo_cb = QCheckBox(self.central_widget) self.cmo_cb.setObjectName("cmo_cb") self.momentum_indicator_layout.addWidget(self.cmo_cb, 2, 0, 1, 1) self.macd_cb = QCheckBox(self.central_widget) self.macd_cb.setObjectName("macd_cb") self.momentum_indicator_layout.addWidget(self.macd_cb, 3, 0, 1, 1) self.roc_cb = QCheckBox(self.central_widget) self.roc_cb.setObjectName("roc_cb") self.momentum_indicator_layout.addWidget(self.roc_cb, 4, 0, 1, 1) self.middle_h_divider = QFrame(self.central_widget) self.middle_h_divider.setFrameShape(QFrame.HLine) self.middle_h_divider.setFrameShadow(QFrame.Sunken) self.middle_h_divider.setObjectName("middle_h_divider") self.options_layout.addLayout(self.momentum_indicator_layout) self.options_layout.addWidget(self.middle_h_divider) # Averages Indicators self.averages_label = QLabel(self.central_widget) self.averages_label.setObjectName("averages_label") self.options_layout.addWidget(self.averages_label) self.wma_cb = QCheckBox(self.central_widget) self.wma_cb.setObjectName("wma_cb") self.options_layout.addWidget(self.wma_cb) self.ema_cb = QCheckBox(self.central_widget) self.ema_cb.setObjectName("ema_cb") self.options_layout.addWidget(self.ema_cb) self.sma_cb = QCheckBox(self.central_widget) self.sma_cb.setObjectName("sma_cb") self.options_layout.addWidget(self.sma_cb) self.hma_cb = QCheckBox(self.central_widget) self.hma_cb.setObjectName("hma_cb") self.options_layout.addWidget(self.hma_cb) self.trix_cb = QCheckBox(self.central_widget) self.trix_cb.setObjectName("trix_cb") self.options_layout.addWidget(self.trix_cb) self.bottom_h_divider = QFrame(self.central_widget) self.bottom_h_divider.setFrameShape(QFrame.HLine) self.bottom_h_divider.setFrameShadow(QFrame.Sunken) self.bottom_h_divider.setObjectName("bottom_h_divider") self.options_layout.addWidget(self.bottom_h_divider) # Trend Indicators self.trend_indicators_label = QLabel(self.central_widget) self.trend_indicators_label.setObjectName("trend_indicators_label") self.options_layout.addWidget(self.trend_indicators_label) self.cci_cb = QCheckBox(self.central_widget) self.cci_cb.setObjectName("cci_cb") self.options_layout.addWidget(self.cci_cb) self.dpo_cb = QCheckBox(self.central_widget) self.dpo_cb.setObjectName("dpo_cb") self.options_layout.addWidget(self.dpo_cb) self.cmf_cb = QCheckBox(self.central_widget) self.cmf_cb.setObjectName("cmf_cb") self.options_layout.addWidget(self.cmf_cb) self.adx_cb = QCheckBox(self.central_widget) self.adx_cb.setObjectName("adx_cb") self.options_layout.addWidget(self.adx_cb) self.force_index_cb = QCheckBox(self.central_widget) self.force_index_cb.setObjectName("checkBox_14") self.options_layout.addWidget(self.force_index_cb) self.display_layout.addLayout(self.options_layout) self.central_layout.addLayout(self.display_layout) self.setCentralWidget(self.central_widget) self.statusbar = QStatusBar(self) self.statusbar.setObjectName("statusbar") self.setStatusBar(self.statusbar) self.retranslateUi() self.setCallbacks() QMetaObject.connectSlotsByName(self)
def paint(self, p, option, index): # QStyledItemDelegate.paint(self, p, option, index) if not index.isValid(): return item = index.internalPointer() self.updateRects(option, index) colors = outlineItemColors(item) style = qApp.style() def _rotate(angle): p.translate(self.mainRect.center()) p.rotate(angle) p.translate(-self.mainRect.center()) # Draw background cg = QPalette.ColorGroup(QPalette.Normal if option.state & QStyle.State_Enabled else QPalette.Disabled) if cg == QPalette.Normal and not option.state & QStyle.State_Active: cg = QPalette.Inactive # Selection if option.state & QStyle.State_Selected: p.save() p.setBrush(option.palette.brush(cg, QPalette.Highlight)) p.setPen(Qt.NoPen) p.drawRoundedRect(option.rect, 12, 12) p.restore() # Stack if item.isFolder() and item.childCount() > 0: p.save() p.setBrush(Qt.white) for i in reversed(range(3)): p.drawRoundedRect(self.itemRect.adjusted(2 * i, 2 * i, -2 * i, 2 * i), 10, 10) p.restore() # Background itemRect = self.itemRect p.save() if settings.viewSettings["Cork"]["Background"] != "Nothing": c = colors[settings.viewSettings["Cork"]["Background"]] col = mixColors(c, QColor(Qt.white), .2) p.setBrush(col) else: p.setBrush(Qt.white) pen = p.pen() pen.setWidth(2) p.setPen(pen) p.drawRoundedRect(itemRect, 10, 10) p.restore() # Title bar topRect = self.topRect p.save() if item.isFolder(): color = QColor(Qt.darkGreen) else: color = QColor(Qt.blue).lighter(175) p.setPen(Qt.NoPen) p.setBrush(color) p.setClipRegion(QRegion(topRect)) p.drawRoundedRect(itemRect, 10, 10) # p.drawRect(topRect) p.restore() # Label color if settings.viewSettings["Cork"]["Corner"] != "Nothing": p.save() color = colors[settings.viewSettings["Cork"]["Corner"]] p.setPen(Qt.NoPen) p.setBrush(color) p.setClipRegion(QRegion(self.labelRect)) p.drawRoundedRect(itemRect, 10, 10) # p.drawRect(topRect) p.restore() p.drawLine(self.labelRect.topLeft(), self.labelRect.bottomLeft()) # One line summary background lineSummary = item.data(Outline.summarySentance.value) fullSummary = item.data(Outline.summaryFull.value) if lineSummary or not fullSummary: m = self.margin r = self.mainLineRect.adjusted(-m, -m, m, m / 2) p.save() p.setPen(Qt.NoPen) p.setBrush(QColor("#EEE")) p.drawRect(r) p.restore() # Border p.save() p.setBrush(Qt.NoBrush) pen = p.pen() pen.setWidth(2) if settings.viewSettings["Cork"]["Border"] != "Nothing": col = colors[settings.viewSettings["Cork"]["Border"]] if col == Qt.transparent: col = Qt.black pen.setColor(col) p.setPen(pen) p.drawRoundedRect(itemRect, 10, 10) p.restore() # Draw the icon iconRect = self.iconRect mode = QIcon.Normal if not option.state & style.State_Enabled: mode = QIcon.Disabled elif option.state & style.State_Selected: mode = QIcon.Selected # index.data(Qt.DecorationRole).paint(p, iconRect, option.decorationAlignment, mode) icon = index.data(Qt.DecorationRole).pixmap(iconRect.size()) if settings.viewSettings["Cork"]["Icon"] != "Nothing": color = colors[settings.viewSettings["Cork"]["Icon"]] colorifyPixmap(icon, color) QIcon(icon).paint(p, iconRect, option.decorationAlignment, mode) # Draw title p.save() text = index.data() titleRect = self.titleRect if text: if settings.viewSettings["Cork"]["Text"] != "Nothing": col = colors[settings.viewSettings["Cork"]["Text"]] if col == Qt.transparent: col = Qt.black p.setPen(col) f = QFont(option.font) # f.setPointSize(f.pointSize() + 1) f.setBold(True) p.setFont(f) fm = QFontMetrics(f) elidedText = fm.elidedText(text, Qt.ElideRight, titleRect.width()) p.drawText(titleRect, Qt.AlignCenter, elidedText) p.restore() # Draw the line bottomRect = self.bottomRect p.save() # p.drawLine(itemRect.x(), iconRect.bottom() + margin, # itemRect.right(), iconRect.bottom() + margin) p.drawLine(bottomRect.topLeft(), bottomRect.topRight()) p.restore() # Lines if True: p.save() p.setPen(QColor("#EEE")) fm = QFontMetrics(option.font) h = fm.lineSpacing() l = self.mainTextRect.topLeft() + QPoint(0, h) while self.mainTextRect.contains(l): p.drawLine(l, QPoint(self.mainTextRect.right(), l.y())) l.setY(l.y() + h) p.restore() # Draw status mainRect = self.mainRect status = item.data(Outline.status.value) if status: it = mainWindow().mdlStatus.item(int(status), 0) if it != None: p.save() p.setClipRegion(QRegion(mainRect)) f = p.font() f.setPointSize(f.pointSize() + 12) f.setBold(True) p.setFont(f) p.setPen(QColor(Qt.red).lighter(175)) _rotate(-35) p.drawText(mainRect, Qt.AlignCenter, it.text()) p.restore() # Draw Summary # One line if lineSummary: p.save() f = QFont(option.font) f.setItalic(True) p.setFont(f) fm = QFontMetrics(f) elidedText = fm.elidedText(lineSummary, Qt.ElideRight, self.mainLineRect.width()) p.drawText(self.mainLineRect, Qt.AlignCenter, elidedText) p.restore() # Full summary if fullSummary: p.setFont(option.font) p.drawText(self.mainTextRect, Qt.TextWordWrap, fullSummary)
def setMaxHeight(self, nRows): metric = QFontMetrics(self.console.font()) rowHeight = metric.lineSpacing() self.console.setMaximumHeight(nRows * rowHeight) self.parent.setMaximumHeight(nRows * rowHeight)
def fixedHeight(self): nRows = max(self.teCodeBox.toPlainText().count('\n') + 1, 5) qFontMetrics = QFontMetrics(self.teCodeBox.font()) rowHeight = qFontMetrics.lineSpacing() + 5 self.teCodeBox.setFixedHeight(rowHeight * nRows + 10)
def paint(self, p, option, index): # QStyledItemDelegate.paint(self, p, option, index) if not index.isValid(): return item = index.internalPointer() self.updateRects(option, index) colors = outlineItemColors(item) style = qApp.style() def _rotate(angle): p.translate(self.mainRect.center()) p.rotate(angle) p.translate(-self.mainRect.center()) # Draw background cg = QPalette.ColorGroup(QPalette.Normal if option.state & QStyle.State_Enabled else QPalette.Disabled) if cg == QPalette.Normal and not option.state & QStyle.State_Active: cg = QPalette.Inactive # Selection if option.state & QStyle.State_Selected: p.save() p.setBrush(option.palette.brush(cg, QPalette.Highlight)) p.setPen(Qt.NoPen) p.drawRoundedRect(option.rect, 12, 12) p.restore() # Stack if item.isFolder() and item.childCount() > 0: p.save() p.setBrush(Qt.white) for i in reversed(range(3)): p.drawRoundedRect( self.itemRect.adjusted(2 * i, 2 * i, -2 * i, 2 * i), 10, 10) p.restore() # Background itemRect = self.itemRect p.save() if settings.viewSettings["Cork"]["Background"] != "Nothing": c = colors[settings.viewSettings["Cork"]["Background"]] col = mixColors(c, QColor(Qt.white), .2) p.setBrush(col) else: p.setBrush(Qt.white) pen = p.pen() pen.setWidth(2) p.setPen(pen) p.drawRoundedRect(itemRect, 10, 10) p.restore() # Title bar topRect = self.topRect p.save() if item.isFolder(): color = QColor(Qt.darkGreen) else: color = QColor(Qt.blue).lighter(175) p.setPen(Qt.NoPen) p.setBrush(color) p.setClipRegion(QRegion(topRect)) p.drawRoundedRect(itemRect, 10, 10) # p.drawRect(topRect) p.restore() # Label color if settings.viewSettings["Cork"]["Corner"] != "Nothing": p.save() color = colors[settings.viewSettings["Cork"]["Corner"]] p.setPen(Qt.NoPen) p.setBrush(color) p.setClipRegion(QRegion(self.labelRect)) p.drawRoundedRect(itemRect, 10, 10) # p.drawRect(topRect) p.restore() if color != Qt.transparent: p.drawLine(self.labelRect.topLeft(), self.labelRect.bottomLeft()) # One line summary background lineSummary = item.data(Outline.summarySentence.value) fullSummary = item.data(Outline.summaryFull.value) if lineSummary or not fullSummary: m = self.margin r = self.mainLineRect.adjusted(-m, -m, m, m / 2) p.save() p.setPen(Qt.NoPen) p.setBrush(QColor("#EEE")) p.drawRect(r) p.restore() # Border p.save() p.setBrush(Qt.NoBrush) pen = p.pen() pen.setWidth(2) if settings.viewSettings["Cork"]["Border"] != "Nothing": col = colors[settings.viewSettings["Cork"]["Border"]] if col == Qt.transparent: col = Qt.black pen.setColor(col) p.setPen(pen) p.drawRoundedRect(itemRect, 10, 10) p.restore() # Draw the icon iconRect = self.iconRect mode = QIcon.Normal if not option.state & style.State_Enabled: mode = QIcon.Disabled elif option.state & style.State_Selected: mode = QIcon.Selected # index.data(Qt.DecorationRole).paint(p, iconRect, option.decorationAlignment, mode) icon = index.data(Qt.DecorationRole).pixmap(iconRect.size()) if settings.viewSettings["Cork"]["Icon"] != "Nothing": color = colors[settings.viewSettings["Cork"]["Icon"]] colorifyPixmap(icon, color) QIcon(icon).paint(p, iconRect, option.decorationAlignment, mode) # Draw title p.save() text = index.data() titleRect = self.titleRect if text: if settings.viewSettings["Cork"]["Text"] != "Nothing": col = colors[settings.viewSettings["Cork"]["Text"]] if col == Qt.transparent: col = Qt.black p.setPen(col) f = QFont(option.font) # f.setPointSize(f.pointSize() + 1) f.setBold(True) p.setFont(f) fm = QFontMetrics(f) elidedText = fm.elidedText(text, Qt.ElideRight, titleRect.width()) p.drawText(titleRect, Qt.AlignCenter, elidedText) p.restore() # Draw the line bottomRect = self.bottomRect p.save() # p.drawLine(itemRect.x(), iconRect.bottom() + margin, # itemRect.right(), iconRect.bottom() + margin) p.drawLine(bottomRect.topLeft(), bottomRect.topRight()) p.restore() # Lines if True: p.save() p.setPen(QColor("#EEE")) fm = QFontMetrics(option.font) h = fm.lineSpacing() l = self.mainTextRect.topLeft() + QPoint(0, h) while self.mainTextRect.contains(l): p.drawLine(l, QPoint(self.mainTextRect.right(), l.y())) l.setY(l.y() + h) p.restore() # Draw status mainRect = self.mainRect status = item.data(Outline.status.value) if status: it = mainWindow().mdlStatus.item(int(status), 0) if it != None: p.save() p.setClipRegion(QRegion(mainRect)) f = p.font() f.setPointSize(f.pointSize() + 12) f.setBold(True) p.setFont(f) p.setPen(QColor(Qt.red).lighter(175)) _rotate(-35) p.drawText(mainRect, Qt.AlignCenter, it.text()) p.restore() # Draw Summary # One line if lineSummary: p.save() f = QFont(option.font) f.setItalic(True) p.setFont(f) fm = QFontMetrics(f) elidedText = fm.elidedText(lineSummary, Qt.ElideRight, self.mainLineRect.width()) p.drawText(self.mainLineRect, Qt.AlignCenter, elidedText) p.restore() # Full summary if fullSummary: p.setFont(option.font) p.drawText(self.mainTextRect, Qt.TextWordWrap, fullSummary)
def paint(self, painter, option, index): dlg = index.model().data(index, Qt.DisplayRole) painter.setRenderHint(QPainter.Antialiasing) color = QColor(Qt.white) if option.state & QStyle.State_MouseOver: color = QColor(variables.HIGHLIGHT_COLOR) painter.setPen(QPen(color)) painter.setBrush(QBrush(color)) painter.drawRect(option.rect) painter.setPen(Qt.black) painter.setBrush(Qt.NoBrush) painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight()) doc = QTextDocument(dlg.ip) doc.setDocumentMargin(0) doc.setDefaultFont(variables.font) textrect = QRect(option.rect) textrect = textrect.marginsRemoved(variables.IP_PADDING) textrect.setHeight(int(doc.size().height())) textrect.setWidth(int(doc.size().width())) offset = textrect.marginsAdded(variables.IP_PADDING).height() painter.setPen(Qt.black) painter.setFont(variables.font) painter.translate(textrect.x(), textrect.y()) textrectf = QRectF(textrect) textrectf.moveTo(0, 0) doc.drawContents(painter, textrectf) painter.translate(-textrect.x(), -textrect.y()) string = "" if dlg.user == variables.USER_ME: string += "You: " print(dlg.msg) string += dlg.msg fm = QFontMetrics(variables.font_small) textrect = QRect(option.rect) textrect.moveTop(textrect.y() + offset) textrect = textrect.marginsRemoved(variables.MSG_PADDING) textrect.setHeight(fm.lineSpacing()) spainter = QStylePainter(painter.device(), QWidget()) spainter.setRenderHint(QPainter.Antialiasing) if fm.horizontalAdvance(string) > textrect.width(): fade = QLinearGradient(variables.MSG_PADDING.left() + textrect.width()* 0.9, 0, variables.MSG_PADDING.left() + textrect.width(), 0) fade.setSpread(QGradient.PadSpread) fade.setColorAt(0, Qt.darkGray) fade.setColorAt(1, color) pal = QPalette() pal.setBrush(QPalette.Text, QBrush(fade)) spainter.setFont(variables.font_small) spainter.drawItemText(textrect, Qt.TextSingleLine, pal, True, string, QPalette.Text) else: spainter.setPen(Qt.darkGray) spainter.setFont(variables.font_small) spainter.drawText(textrect, Qt.TextSingleLine, string) p1 = textrect.bottomRight() + QPoint(36, -int(textrect.height() / 2)) if dlg.status == variables.STATUS_UNREAD: spainter.setPen(Qt.NoPen) spainter.setBrush(QColor(variables.STATUS_COLOR)) spainter.drawEllipse(p1, 7, 7) elif dlg.status == variables.STATUS_UNDELIVERED: pen = QPen(QColor(variables.STATUS_COLOR)) pen.setWidth(2) spainter.setPen(pen) spainter.setBrush(Qt.NoBrush) spainter.drawEllipse(p1, 7, 7) spainter.drawLine(p1, p1 + QPoint(0, -5)) spainter.drawLine(p1, p1 + QPoint(3, 0)) elif dlg.status == variables.STATUS_NEW: pen = QPen(QColor(variables.STATUS_NEW_COLOR)) pen.setWidth(5) spainter.setPen(pen) spainter.setBrush(Qt.NoBrush) spainter.drawEllipse(p1, 7, 7) #painter.translate(-textrect.x(), -textrect.y()) '''doc = QTextDocument(str)
def get_text_edit_row_height(editor: QPlainTextEdit, rows: int) -> int: metrics = QFontMetrics(editor.document().defaultFont()) margins = editor.contentsMargins() return int(metrics.lineSpacing() * rows + (editor.document().documentMargin() + editor.frameWidth()) * 2 + margins.top() + margins.bottom() + 1)