def paintEvent(self, event): super(MySlider, self).paintEvent(event) qp = QPainter(self) pen = QPen() pen.setWidth(2) pen.setColor(Qt.black) qp.setPen(pen) font = QFont('Times', 10) font_y_offset = font.pointSize()/2 qp.setFont(font) size = self.size() contents = self.contentsRect() db_val_list = [10, 5, 0, -5, -10, -20, -30, -40, -50, -60, -90] for val in db_val_list: if val == 10: y_val_fudge = 12 elif val == -90: y_val_fudge = -12 db_scaled = db_to_int(val) y_val = contents.height() - translate(db_scaled, 0, 1023, 0, contents.height()) if val == -90: qp.drawText(contents.x() - font.pointSize(), y_val + font_y_offset + y_val_fudge, '-oo') else: qp.drawText(contents.x() - font.pointSize(), y_val + font_y_offset + y_val_fudge,'{0:2}'.format(val)) qp.drawLine(contents.x() + font.pointSize(), y_val + y_val_fudge, contents.x() + contents.width(), y_val + y_val_fudge)
def fitTextToWidth(text: str, font: QFont, width: int) -> QFont: text_width = QFontMetrics(font).horizontalAdvance(text) step = font.pointSize() / 20 new_font = QFont(font) while text_width > width: new_font.setPointSizeF(max(0, new_font.pointSize() - step)) text_width = QFontMetrics(new_font).horizontalAdvance(text) return new_font
def _fiddle_title_label(self): self.ui.spacer_label.setText(self.ui.big_label.text()) reference_font = QFont() reference_font.setPointSize(reference_font.pointSize() * 2) reference_font.setWeight(QFont.Black) self.ui.big_label.setFont(reference_font) reference_font.setPointSize(reference_font.pointSize() * 2 / 3) self.ui.spacer_label.setFont(reference_font)
def updateUIFromTheme(self): self.txtThemeName.setText(self._themeData["Name"]) # Window Background self.setButtonColor(self.btnThemWindowBackgroundColor, self._themeData["Background/Color"]) i = self.cmbThemeBackgroundImage.findData(self._themeData["Background/ImageFile"], flags=Qt.MatchContains) if i != -1: self.cmbThemeBackgroundImage.setCurrentIndex(i) self.cmbThemBackgroundType.setCurrentIndex(self._themeData["Background/Type"]) # Text background self.setButtonColor(self.btnThemeTextBackgroundColor, self._themeData["Foreground/Color"]) self.spnThemeTextBackgroundOpacity.setValue(self._themeData["Foreground/Opacity"]) self.spnThemeTextMargins.setValue(self._themeData["Foreground/Margin"]) self.spnThemeTextPadding.setValue(self._themeData["Foreground/Padding"]) self.cmbThemeTextPosition.setCurrentIndex(self._themeData["Foreground/Position"]) self.spnThemeTextRadius.setValue(self._themeData["Foreground/Rounding"]) self.spnThemeTextWidth.setValue(self._themeData["Foreground/Width"]) # Text Options self.setButtonColor(self.btnThemeTextColor, self._themeData["Text/Color"]) f = QFont() f.fromString(self._themeData["Text/Font"]) self.cmbThemeFont.setCurrentFont(f) i = self.cmbThemeFontSize.findText(str(f.pointSize())) if i != -1: self.cmbThemeFontSize.setCurrentIndex(i) else: self.cmbThemeFontSize.addItem(str(f.pointSize())) self.cmbThemeFontSize.setCurrentIndex(self.cmbThemeFontSize.count() - 1) self.setButtonColor(self.btnThemeMisspelledColor, self._themeData["Text/Misspelled"]) # Paragraph Options self.chkThemeIndent.setCheckState(Qt.Checked if self._themeData["Spacings/IndentFirstLine"] else Qt.Unchecked) self.spnThemeLineSpacing.setEnabled(False) self.cmbThemeAlignment.setCurrentIndex(self._themeData["Spacings/Alignment"]) if self._themeData["Spacings/LineSpacing"] == 100: self.cmbThemeLineSpacing.setCurrentIndex(0) elif self._themeData["Spacings/LineSpacing"] == 150: self.cmbThemeLineSpacing.setCurrentIndex(1) elif self._themeData["Spacings/LineSpacing"] == 200: self.cmbThemeLineSpacing.setCurrentIndex(2) else: self.cmbThemeLineSpacing.setCurrentIndex(3) self.spnThemeLineSpacing.setEnabled(True) self.spnThemeLineSpacing.setValue(self._themeData["Spacings/LineSpacing"]) self.spnThemeParaAbove.setValue(self._themeData["Spacings/ParagraphAbove"]) self.spnThemeParaBelow.setValue(self._themeData["Spacings/ParagraphBelow"]) self.spnThemeTabWidth.setValue(self._themeData["Spacings/TabWidth"])
def __init__(self, bookmark, parent=None): """ Constructor @param bookmark reference to the bookmark to be shown (Bookmark) @param parent reference to the parent widget (QWidget) """ super(BookmarkInfoDialog, self).__init__(parent) self.setupUi(self) self.__bookmark = bookmark self.icon.setPixmap(UI.PixmapCache.getPixmap("bookmark32.png")) font = QFont() font.setPointSize(font.pointSize() + 2) self.title.setFont(font) if bookmark is None: self.titleEdit.setEnabled(False) else: self.titleEdit.setText(bookmark.title) self.titleEdit.setFocus() msh = self.minimumSizeHint() self.resize(max(self.width(), msh.width()), msh.height())
def main(): path = os.path.dirname(__file__) with open(os.path.join(path, 'config.json'), encoding='utf-8') as f: conf = json.load(f) if os.path.exists(os.path.join(path, 'logs')): logfile = os.path.join(path, 'logs', 'mkepub.log') else: logfile = os.path.expanduser(os.path.join('~', 'mkepub.log')) logging.basicConfig(level=logging.INFO, filename=logfile, filemode='w', format='%(levelname)-8s %(message)s') app = QApplication(sys.argv) font = QFont('宋体') pointsize = font.pointSize() font.setPixelSize(pointsize * 90 / 72) app.setFont(font) win = MainWindow(conf) sys.excepthook = win.exceptHook win.show() try: ret = app.exec_() except Exception: logging.exception('Unhandle exception') ret = 1 sys.exit(ret)
def Update_Font(self, new_font=None): ''' Update up the font to use in the various windows. If called with no arg, this refreshes the current font, useful for when new tabs are created. ''' if new_font == None: new_font = self.current_font else: self.current_font = new_font # Set up a slightly smaller version of the current font. small_font = QFont() # Unclear on how best to get an initial copy; try passing # through strings. small_font.fromString(new_font.toString()) small_font.setPointSize(small_font.pointSize() - 2) # Pass the fonts to tag pages. for widget in self.Get_Tab_Widgets(): widget.Update_Font(new_font, small_font) # Put a small font on the output window. self.widget_output.setFont(small_font) return
def initUi(self): # 初始化界面 font = QFont("雅黑") pointsize = font.pointSize() font.setPixelSize(pointsize * 95 / 72) app.setFont(font) # 通过QListWidget的当前item变化来切换QStackedWidget中的序号 self.listWidget.currentRowChanged.connect( self.stackedWidget.setCurrentIndex) # 去掉边框 self.listWidget.setFrameShape(QListWidget.NoFrame) # 隐藏滚动条 self.listWidget.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.listWidget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # 这里就用一般的文本配合图标模式了(也可以直接用Icon模式,setViewMode) menu = ["首页", "模块设置", "在线识别", "离线检索", "信息查看", "退出系统"] for i, title in enumerate(menu): item = QListWidgetItem(QIcon('Data/%d.ico' % i), title, self.listWidget) # 设置item的默认宽高(这里只有高度比较有用) item.setSizeHint(QSize(16777215, 50)) # 文字居中 item.setTextAlignment(Qt.AlignCenter) # 再模拟20个右侧的页面(就不和上面一起循环放了) for i in range(20): w = QWidget() label2 = QLabel('我是buy页面 %d' % i, w) label2.setAlignment(Qt.AlignCenter) # 设置label的背景颜色(这里随机) # 这里加了一个margin边距(方便区分QStackedWidget和QLabel的颜色) label2.setStyleSheet( 'background: rgb(%d, %d, %d);margin: 50px;' % (randint(0, 120), randint(0, 255), randint(0, 255))) self.stackedWidget.addWidget(w)
def font(xml: QXmlStreamWriter, font: QFont, align: str = "left", rotation: int = 0, tag: str = "font"): xml.writeStartElement("font") xml.writeAttribute("family", font.family()) if font.style() == QFont.StyleItalic: xml.writeAttribute("style", "italic") elif font.style() == QFont.StyleOblique: xml.writeAttribute("style", "oblique") else: xml.writeAttribute("style", "normal") xml.writeAttribute("size", str(font.pointSize())) v = [ "bold", "bolder", "lighter", "100", "200", "300", "400", "500", "600", "700", "800", "900", "900" ] if font.weight() <= 50: xml.writeAttribute("weight", "normal") else: xml.writeAttribute("weight", v[int((font.weight() - 50) / 4)]) dec = [] if font.underline(): dec.append("underline") if font.overline(): dec.append("overline") if font.strikeOut(): dec.append("line-through") if len(dec) > 0: xml.writeAttribute("decoration", ";".join(dec)) xml.writeAttribute("align", align) xml.writeAttribute("rotation", str(rotation)) xml.writeEndElement() #fecha font
def draw_frequency_marker(self, x_pos, frequency): if frequency is None: self.clear_frequency_marker() return y1 = self.sceneRect().y() y2 = self.sceneRect().y() + self.sceneRect().height() if self.frequency_marker is None: pen = QPen(constants.LINECOLOR, 0) self.frequency_marker = [None, None] self.frequency_marker[0] = self.addLine(x_pos, y1, x_pos, y2, pen) self.frequency_marker[1] = self.addSimpleText("") self.frequency_marker[1].setBrush(QBrush(constants.LINECOLOR)) font = QFont() font.setBold(True) font.setPointSize(int(font.pointSize() * 1.25)+1) self.frequency_marker[1].setFont(font) self.frequency_marker[0].setLine(x_pos, y1, x_pos, y2) scale_x, scale_y = util.calc_x_y_scale(self.sceneRect(), self.parent()) self.frequency_marker[1].setTransform(QTransform.fromScale(scale_x, scale_y), False) self.frequency_marker[1].setText("Tune to " + Formatter.big_value_with_suffix(frequency, decimals=3)) font_metric = QFontMetrics(self.frequency_marker[1].font()) text_width = font_metric.width("Tune to") * scale_x text_width += (font_metric.width(" ") * scale_x) / 2 self.frequency_marker[1].setPos(x_pos-text_width, 0.95*y1)
def __init__(self, app): super().__init__() self.app = app self.async_fetch = AsyncFetch(CachedHttpClient(HttpClient(), 'cache')) self.async_fetch.ready.connect(self.on_fetch_ready) self.comboxBox = QComboBox(self) self.comboxBox.setEditable(True) self.comboxBox.setCurrentText('') self.comboxBox.currentTextChanged.connect(self.on_text_changed) font = QFont() font.setPointSize(font.pointSize() + ADD_TO_FONT_SIZE) self.comboxBox.setFont(font) self.browser = QTextBrowser(self) self.browser.setText(STYLE + HTML) self.browser.show() mainLayout = QVBoxLayout(self) mainLayout.setSpacing(0) mainLayout.setContentsMargins(0, 0, 0, 0) mainLayout.addWidget(self.comboxBox) mainLayout.addWidget(self.browser) self.setLayout(mainLayout) self.setWindowTitle('OrdbokUibNo') self.resize(WINDOW_WIDTH, WINDOW_HEIGHT) self.setWindowIcon(QIcon(ICON_FILENAME)) QTimer.singleShot(1, self.center) self.center() self.show()
def setThemeEditorDatas(editor, themeDatas, pixmap, screenRect): textRect = themeTextRect(themeDatas, screenRect) x, y, width, height = themeEditorGeometry(themeDatas, textRect) editor.setGeometry(x, y, width, height) # p = editor.palette() ##p.setBrush(QPalette.Base, QBrush(pixmap.copy(x, y, width, height))) # p.setBrush(QPalette.Base, QColor(Qt.transparent)) # p.setColor(QPalette.Text, QColor(themeDatas["Text/Color"])) # p.setColor(QPalette.Highlight, QColor(themeDatas["Text/Color"])) # p.setColor(QPalette.HighlightedText, Qt.black if qGray(QColor(themeDatas["Text/Color"]).rgb()) > 127 else Qt.white) # editor.setPalette(p) editor.setAttribute(Qt.WA_NoSystemBackground, True) bf = getThemeBlockFormat(themeDatas) editor.setDefaultBlockFormat(bf) # b = editor.document().firstBlock() # cursor = editor.textCursor() # cursor.setBlockFormat(bf) # while b.isValid(): # bf2 = b.blockFormat() # bf2.merge(bf) # cursor.setPosition(b.position()) ##cursor.setPosition(b.position(), QTextCursor.KeepAnchor) # cursor.setBlockFormat(bf2) # b = b.next() editor.setTabStopWidth(themeDatas["Spacings/TabWidth"]) editor.document().setIndentWidth(themeDatas["Spacings/TabWidth"]) editor.highlighter.setMisspelledColor(QColor(themeDatas["Text/Misspelled"])) cf = QTextCharFormat() # f = QFont() # f.fromString(themeDatas["Text/Font"]) # cf.setFont(f) editor.highlighter.setDefaultCharFormat(cf) f = QFont() f.fromString(themeDatas["Text/Font"]) # editor.setFont(f) editor.setStyleSheet(""" background: transparent; color: {foreground}; font-family: {ff}; font-size: {fs}; selection-color: {sc}; selection-background-color: {sbc}; """.format( foreground=themeDatas["Text/Color"], ff=f.family(), fs="{}pt".format(str(f.pointSize())), sc="black" if qGray(QColor(themeDatas["Text/Color"]).rgb()) > 127 else "white", sbc=themeDatas["Text/Color"], ) ) editor._fromTheme = True
def draw_frequency_marker(self, x_pos, frequency): if frequency is None: self.clear_frequency_marker() return y1 = self.sceneRect().y() y2 = self.sceneRect().y() + self.sceneRect().height() if self.frequency_marker is None: pen = QPen(constants.LINECOLOR, 0) self.frequency_marker = [None, None] self.frequency_marker[0] = self.addLine(x_pos, y1, x_pos, y2, pen) self.frequency_marker[1] = self.addSimpleText("") self.frequency_marker[1].setBrush(QBrush(constants.LINECOLOR)) font = QFont() font.setBold(True) font.setPointSize(int(font.pointSize() * 1.25)+1) self.frequency_marker[1].setFont(font) self.frequency_marker[0].setLine(x_pos, y1, x_pos, y2) scale_x, scale_y = self.__calc_x_y_scale(self.sceneRect()) self.frequency_marker[1].setTransform(QTransform.fromScale(scale_x, scale_y), False) self.frequency_marker[1].setText("Tune to " + Formatter.big_value_with_suffix(frequency, decimals=3)) font_metric = QFontMetrics(self.frequency_marker[1].font()) text_width = font_metric.width("Tune to") * scale_x text_width += (font_metric.width(" ") * scale_x) / 2 self.frequency_marker[1].setPos(x_pos-text_width, 0.95*y1)
def minimumSizeHint(self): font = QFont(self.font()) font.setPointSize(font.pointSize() - 1) fm = QFontMetricsF(font) return QSize( fm.width(FractionSlider.WSTRING) * self.__denominator, (fm.height() * 4) + FractionSlider.YMARGIN)
class Widget(QWidget): def __init__(self, text): super().__init__() self.text = text self.mask = "⚃" self.masked = True self.font = QFont() self.font.setPointSize(10) self.setWindowFlags(Qt.Tool | Qt.FramelessWindowHint) self.setAttribute(Qt.WA_TranslucentBackground) self.updateMove() def updateMove(self): a = QDesktopWidget().screenGeometry() if (self.masked == False): self.resize(QFontMetrics(self.font).width(self.text), 30) else: self.resize( QFontMetrics(self.font).width(self.mask) if QFontMetrics(self.font).width(self.mask) > 30 else 30, 30) self.move(a.width() - self.width(), a.height() - self.height()) def leaveEvent(self, event): self.masked = True self.updateMove() self.update() def enterEvent(self, event): self.masked = False self.updateMove() self.update() def paintEvent(self, event): qt = QPainter(self) qt.setPen(QColor(0xffffff)) if (self.masked == False): qt.drawText( self.width() * 0.5 - QFontMetrics(self.font).width(self.text) * 0.45, self.height() * 0.5 + self.font.pointSize() * 0.5, self.text) else: qt.drawText( self.width() * 0.5 - QFontMetrics(self.font).width(self.mask) * 0.45, self.height() * 0.5 + self.font.pointSize() * 0.5, self.mask)
def setupUi(self): """ Setup the application UI. """ self.resize(QGuiApplication.primaryScreen().availableSize() * 2 / 3) # Instanciate the image viewer. self.imageView = ImageView() # Get the system font size font = QFont() size = font.pointSize() # Increase size. font.setPointSize(size + 2) # Create a label to display the images. self.introLabel = QLabel("Press Ctrl+O to select an image" "\nOr choose a directory by pressing Ctrl+D") self.introLabel.setAlignment(Qt.AlignCenter) self.introLabel.setFont(font) # Create the index area. # Button - Text - Button # A frame to draw a line around the layout. self.indexBox = IndexBox() self.buttonPrevious = IndexButton("Previous") self.buttonPrevious.setEnabled(False) self.buttonPrevious.clicked.connect(self.previousImage) self.labelIndex = QLabel() self.labelIndex.setAlignment(Qt.AlignCenter) self.buttonNext = IndexButton("Next") self.buttonNext.setEnabled(False) self.buttonNext.clicked.connect(self.nextImage) frameLayout = QHBoxLayout() frameLayout.addWidget(self.buttonPrevious) frameLayout.addWidget(self.labelIndex) frameLayout.addWidget(self.buttonNext) self.indexBox.setLayout(frameLayout) # Create and add widgets to the main layout. self.mainLayout = QVBoxLayout() self.mainLayout.setContentsMargins(0, 0, 0, 0) self.mainLayout.setSpacing(0) self.mainLayout.addWidget(self.introLabel) self.mainLayout.addWidget(self.indexBox) # Create central widget. centralWidget = QWidget() centralWidget.setLayout(self.mainLayout) self.setCentralWidget(centralWidget)
class systemSettings(QFrame): def __init__(self, target): super().__init__(target) #[pname, bool: active] self.parameters = [] self.scrool = 0 self.theme = target.theme self.font = QFont() self.font.setPointSize(10) self.padding = 5 self.d_padding = 6 self.listener = None def clear(self): self.parameters = [] def paintEvent(self, event): painter = QPainter(self) painter.fillRect(0, 0, self.width(), self.height(), QColor(self.theme[1])) q_line = self.padding for parameter in self.parameters: painter.fillRect(self.padding, q_line, self.font.pointSize()+self.d_padding, self.font.pointSize()+self.d_padding, QColor(self.theme[8][0])) if(parameter[1]): painter.fillRect(self.padding+self.d_padding*0.5, q_line+self.d_padding*0.5, self.font.pointSize(), self.font.pointSize(), QColor(self.theme[8][1])) q_line += self.font.pointSize()+self.d_padding painter.drawText(self.padding * 2 + self.d_padding + self.font.pointSize(), q_line - self.font.pointSize() * 0.5 + self.d_padding * 0.5, parameter[0]) def addParameter(self, pname, active): self.parameters.append([pname, active]) def mousePressEvent(self, event): x = event.x() y = event.y() q_line = self.padding for i in range(0, len(self.parameters)): dp = self.padding if(x > dp and x < dp+self.font.pointSize()+self.d_padding and y > q_line and y < q_line + self.font.pointSize()+self.d_padding): self.parameters[i][1] = not self.parameters[i][1] if(self.listener != None): self.listener(i, self.parameters, self.parameters[i][1]) self.update() return q_line += self.font.pointSize()+self.d_padding
def paintEvent(self, event=None): font = QFont(self.font()) font.setPointSize(font.pointSize() - 1) fm = QFontMetricsF(font) fracWidth = fm.width(FractionSlider.WSTRING) indent = fm.boundingRect("9").width() / 2.0 if not X11: fracWidth *= 1.5 span = self.width() - (FractionSlider.XMARGIN * 2) value = self.__numerator / float(self.__denominator) painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) painter.setRenderHint(QPainter.TextAntialiasing) painter.setPen(self.palette().color(QPalette.Mid)) painter.setBrush(self.palette().brush(QPalette.AlternateBase)) painter.drawRect(self.rect()) segColor = QColor(Qt.green).darker(120) segLineColor = segColor.darker() painter.setPen(segLineColor) painter.setBrush(segColor) painter.drawRect(FractionSlider.XMARGIN, FractionSlider.YMARGIN, span, fm.height()) textColor = self.palette().color(QPalette.Text) segWidth = span / self.__denominator segHeight = fm.height() * 2 nRect = fm.boundingRect(FractionSlider.WSTRING) x = FractionSlider.XMARGIN yOffset = segHeight + fm.height() for i in range(self.__denominator + 1): painter.setPen(segLineColor) painter.drawLine(x, FractionSlider.YMARGIN, x, segHeight) painter.setPen(textColor) y = segHeight rect = QRectF(nRect) rect.moveCenter(QPointF(x, y + fm.height() / 2.0)) # painter.drawText(rect, Qt.AlignCenter, # QString.number(i)) painter.drawText(rect, Qt.AlignCenter, str(i)) y = yOffset rect.moveCenter(QPointF(x, y + fm.height() / 2.0)) painter.drawText(rect, Qt.AlignCenter, str(self.__denominator)) painter.drawLine(QPointF(rect.left() + indent, y), QPointF(rect.right() - indent, y)) x += segWidth span = int(span) y = FractionSlider.YMARGIN - 0.5 triangle = [ QPointF(value * span, y), QPointF((value * span) + (2 * FractionSlider.XMARGIN), y), QPointF((value * span) + FractionSlider.XMARGIN, fm.height()) ] painter.setPen(Qt.yellow) painter.setBrush(Qt.darkYellow) painter.drawPolygon(QPolygonF(triangle))
def DecreaseFont(self): FontIs = self.textEdit.currentFont() font = QFont(FontIs) FontSize = int(font.pointSize()) FontFam = font.family() if FontSize > 6: FontSize -= 1 font.setPointSize(FontSize) font.setFamily(FontFam) self.textEdit.setFont(font)
def minimumSizeHint(self): '''定义字体、字体大小、根据字体Metrics的大小返回一个QSize对象,设置最小的尺寸''' font = QFont(self.font()) # 这声明了和没有声明有什么区别?Constructs a font that is a copy of font. # self.font() This property describes the widget's requested font. # font = QFont() # 只需要一个实例,因为此函数的目的是返回一个QSize font.setPointSize(font.pointSize() - 1) # The point size must be greater than zero. # pointSize() Returns -1 if the font size was specified in pixels. fm = QFontMetricsF(font) # print(fm.height(),fm.width(FractionSlider.WSTRING),fm.width(FractionSlider.WSTRING+'666')) # Return 11.0 18.0 36.0 return QSize(fm.width(FractionSlider.WSTRING) * self.__denominator, (fm.height() * 4) + FractionSlider.YMARGIN)
def createEditor(self, parent, option, index): self.updateRects(option, index) bgColor = self.bgColors.get(index, "white") if self.mainLineRect.contains(self.lastPos): # One line summary self.editing = Outline.summarySentence edt = QLineEdit(parent) edt.setFocusPolicy(Qt.StrongFocus) edt.setFrame(False) f = QFont(option.font) if self.newStyle(): f.setBold(True) else: f.setItalic(True) edt.setAlignment(Qt.AlignCenter) edt.setPlaceholderText(self.tr("One line summary")) edt.setFont(f) edt.setStyleSheet("background: {}; color: black;".format(bgColor)) return edt elif self.titleRect.contains(self.lastPos): # Title self.editing = Outline.title edt = QLineEdit(parent) edt.setFocusPolicy(Qt.StrongFocus) edt.setFrame(False) f = QFont(option.font) if self.newStyle(): f.setPointSize(f.pointSize() + 4) else: edt.setAlignment(Qt.AlignCenter) f.setBold(True) edt.setFont(f) edt.setStyleSheet("background: {}; color: black;".format(bgColor)) # edt.setGeometry(self.titleRect) return edt else: # self.mainTextRect.contains(self.lastPos): # Summary self.editing = Outline.summaryFull edt = QPlainTextEdit(parent) edt.setFocusPolicy(Qt.StrongFocus) edt.setFrameShape(QFrame.NoFrame) try: # QPlainTextEdit.setPlaceholderText was introduced in Qt 5.3 edt.setPlaceholderText(self.tr("Full summary")) except AttributeError: pass edt.setStyleSheet("background: {}; color: black;".format(bgColor)) return edt
def paintCells(self): painter = QPainter() painter.begin(self) painter.setBrush(QBrush(Qt.red, Qt.DiagCrossPattern)) painter.setPen(QPen(Qt.black, 5, Qt.SolidLine)) font = QFont() font.setPointSize(font.pointSize() * 4) painter.setFont(font) for i in range(0, len(self.coordinates)): painter.drawRect(*(self.coordinates[i])) center_x = (self.coordinates[i][0] + self.coordinates[i][2])/2 center_y = (self.coordinates[i][1] + self.coordinates[i][3])/2 painter.drawText(center_x, center_y, f'{i}') painter.end()
def test_1(self): font = QFont("Arial", 88) def continueFunc(dialog): page = dialog._pageForItem["Editor/Font"] page.lFont.setFont(font) QTest.keyClick(dialog, Qt.Key_Enter) self.openSettings(continueFunc) self.assertEqual(core.config()['Qutepart']['Font']['Family'], font.family()) self.assertEqual(core.config()['Qutepart']['Font']['Size'], font.pointSize()) self.assertEqual(core.workspace().currentDocument().qutepart.font().family(), font.family()) self.assertEqual(core.workspace().currentDocument().qutepart.font().pointSize(), font.pointSize())
def create_box_strategy(self): ls = [m[0] for m in inspect.getmembers(strategies, inspect.isclass) ] # if m[1].__module__ == 'strategies'] self.strategy_choice = QComboBox() font = QFont() font.setPointSize(font.pointSize() + 10) self.strategy_choice.setFont(font) self.strategy_choice.highlighted[str].connect(self.strategy_selected) self.strategy_choice.insertItem(0, 'SomeStrategy') self.strategy_choice.insertItem(1, 'SomeStrateg2y') strategy_box = QHBoxLayout() strategy_box.addWidget(self.strategy_choice) strategy_box.addStretch(1) return strategy_box
def __init__(self, app): super().__init__() self.ticket = None self.app = app self.comboxBox = QComboBox(self) self.comboxBox.setEditable(True) # self.comboxBox.setCom self.comboxBox.addItems(slurp_lines(CANDIDATES_FILENAME)) self.comboxBox.setMaximumWidth(WINDOW_WIDTH) self.comboxBox.setCurrentText('') # self.completer.setCaseSensitivity(Qt.CaseInsensitive) self.custom_filter = ExactMultipartFilterModel(self) self.custom_filter.setSourceModel(self.comboxBox.model()) self.comboxBox.lineEdit().textEdited.connect( self.custom_filter.setFilterString) font = QFont() font.setPointSize(font.pointSize() + ADD_TO_FONT_SIZE) self.comboxBox.setFont(font) self.completer = QCompleter(self.comboxBox.model(), self.comboxBox) self.completer.setModel(self.custom_filter) self.completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion) self.completer.popup().setFont(font) self.comboxBox.setCompleter(self.completer) mainLayout = QVBoxLayout(self) # mainLayout.addStretch(1) mainLayout.setSpacing(0) # mainLayout.setMargin(0) mainLayout.setContentsMargins(0, 0, 0, 0) # mainLayout.setMar mainLayout.addWidget(self.comboxBox) self.setLayout(mainLayout) self.setWindowTitle('CompleteBox') self.resize(WINDOW_WIDTH, WINDOW_HEIGHT) self.setWindowIcon(QIcon(ICON_FILENAME)) self.center() self.show()
class ItemPrintDatasource: # If we want to print tables and trees with a good code re-use, we've got to abstract away the # fact that trees have nodes and stuff and start treating it as rows and columns, with some # cells having more indentation than others. That's what this class is about.: def __init__(self, printViewModel, baseFont): self.printViewModel = printViewModel # From core.gui.transaction_print self._rowFont = QFont(baseFont) self._splitFont = QFont(baseFont) self._splitFont.setPointSize(self._splitFont.pointSize()-2) self._headerFont = QFont(self._rowFont) self._headerFont.setBold(True) def columnCount(self): """Returns the number of columns *to print*.""" raise NotImplementedError() def rowCount(self): """Returns the number of rows *to print*.""" raise NotImplementedError() def splitCount(self, rowIndex): raise NotImplementedError() def splitValues(self, rowIndex, splitIndex): raise NotImplementedError() def data(self, rowIndex, colIndex, role): """Returns model data for the index at the *printable* (rowIndex, colIndex) cell.""" raise NotImplementedError() def columnAtIndex(self, colIndex): """Returns the Column instance at index `colIndex`""" raise NotImplementedError() def indentation(self, rowIndex, colIndex): """Returns the indentation pixels for the (rowIndex, colIndex).""" return 0 def rowFont(self): return self._rowFont def splitFont(self): return self._splitFont def headerFont(self): return self._headerFont
def _create_pie_chart(self, project_data: tuple): font = QFont("黑体") point_size = font.pointSize() font.setPixelSize(point_size * 90 / 72) self.char_view = QChartView(self) # 将父窗体设置为空,设置为独立窗口 self.char_view.setFont(font) self.char_view.setGeometry(100, 100, 800, 600) # 设置窗口位置和大小 self.char_view.setRenderHint(QPainter.Antialiasing) # 消除锯齿 pie = self.get_data(project_data) # 获取区域种类及占比信息 pie_series = self.set_slice(pie, project_data) # 绘制饼状图各区间 self.char_view.chart().addSeries(pie_series) # 将饼状图添加至charView中 self.char_view.chart().setTitle("各类型地物占比") # 设置标题 self.char_view.chart().legend().hide() self._layout.addWidget(self.char_view)
class HttpMsgDialog(QDialog): signal_font_size = pyqtSignal(int) def __init__(self, parent=None, font_size=12): super().__init__(parent) self.ui = Ui_Dialog() self.ui.setupUi(self) self.row_msg = '' self.decode_msg = '' self.font = QFont() self.font.setPointSize(font_size) self.ui.spinbox_font_size.setValue(self.font.pointSize()) def msg(self, text, match_pattern): self.row_msg = text self.decode_msg = parse.unquote(self.row_msg) self.ui.tb_row.setPlainText(self.row_msg) self.ui.tb_decoded.setText(self.decode_msg) # 33,67,1,4,27,>'"><script>alert(6710)</script>?merchandiseCode=295685493008404483||||| # 'None'值 if match_pattern != 'None': pattern_str = match_pattern.split(',')[5].strip('|||||') pattern_index = self.decode_msg.find(pattern_str) pattern_str_len = int(match_pattern.split(',')[1]) text_cursor = self.ui.tb_decoded.textCursor() text_cursor.setPosition(pattern_index) self.ui.tb_decoded.setTextCursor(text_cursor) # 通过起始index和锚点选中匹配特征 text_cursor.setPosition(pattern_index + pattern_str_len, QTextCursor.KeepAnchor) self.ui.tb_decoded.setTextCursor(text_cursor) self.ui.tb_decoded.setTextColor(Qt.red) text_cursor.clearSelection() self.ui.tb_decoded.setTextCursor(text_cursor) @pyqtSlot(int) def on_spinbox_font_size_valueChanged(self, v): self.signal_font_size.emit(v) self.font.setPointSize(v) self.ui.tb_decoded.setFont(self.font) self.ui.tb_row.setFont(self.font)
def downloading(self, msg): # print('downloading...') # self.modalWindowDownloading = QWidget(window, Qt.Window) # self.modalWindowDownloading.setWindowModality(Qt.WindowModal) # Ui_FormDownload.setupUi(self, self.modalWindowDownloading) # Ui_FormDownload.retranslateUi(self, self.modalWindowDownloading) # self.modalWindowDownloading.show() image = QPixmap('./pic/loading1.jpg') self.splash = QSplashScreen(image) self.splash.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.splash = QSplashScreen(image, Qt.WindowStaysOnTopHint) self.splash.setMask(image.mask()) font = QFont(self.splash.font()) font.setPointSize(font.pointSize() + 3) self.splash.setFont(font) self.splash.showMessage(msg, QtCore.Qt.AlignTop | QtCore.Qt.AlignCenter, QtCore.Qt.black) self.splash.show()
def __init__(self, parent): super().__init__(parent) # QScintilla only uses the primary font family rather than searching through alternatives. # So we need to do this manually... db = QFontDatabase() fonts = set(db.families(QFontDatabase.WritingSystem.Latin)) for font_name in self._FONTS: if font_name in fonts: font = QFont(font_name, 10) break else: font = db.systemFont(QFontDatabase.FixedFont) self.setDefaultFont(font) for style, (color, font_kwargs) in self._STYLE_SETTINGS.items(): self.setColor(QColor(color), style) self.setFont(QFont(font.family(), font.pointSize(), **font_kwargs), style) self.getStyling = partial(parent.SendScintilla, QsciScintilla.SCI_GETSTYLEAT)
def updateFont(self): """Updated the GUI's font style from settings, """ theFont = QFont() if self.mainConf.guiFont not in self.guiFontDB.families(): if self.mainConf.osWindows: # On Windows, default to Cantarell provided by novelWriter theFont.setFamily("Cantarell") theFont.setPointSize(11) else: theFont = self.guiFontDB.systemFont(QFontDatabase.GeneralFont) self.mainConf.guiFont = theFont.family() self.mainConf.guiFontSize = theFont.pointSize() else: theFont.setFamily(self.mainConf.guiFont) theFont.setPointSize(self.mainConf.guiFontSize) qApp.setFont(theFont) return
def __init__(self, parent: QWidget): super(ActiveAlertsWidget, self).__init__(parent, "Active alerts", _ICON_OK) self._content = QLabel() self._content.setWordWrap(True) self._content.setAlignment(Qt.AlignCenter) font = QFont() font.setBold(True) font.setPointSize(round(font.pointSize() * 0.8)) self._content.setFont(font) layout = QVBoxLayout() layout.addStretch(1) layout.addWidget(self._content) layout.addStretch(1) layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) self.reset()
def get_good_font_size( # TODO increase stability and speed self, font: QtGui.QFont, rect: QtCore.QRect, text: str, *, step=5, max_size=80, min_size=0 ) -> int: """Return the max size of the font that text can fit""" current_font_size = max_size + 5 # Set max size of the font while True: # Iterate size font while it fit into additional window current_font_size -= 5 font.setPointSize(current_font_size) font_metrics = QtGui.QFontMetrics(font) sized_rect = font_metrics.boundingRect( # Return rect of text with rect, # current font QtCore.Qt.AlignCenter | QtCore.Qt.TextWordWrap, text ) if (sized_rect.height() < rect.height() # Check if font is not and sized_rect.width() < rect.width()): # too large break return font.pointSize()
def updateFont(self): """Update the GUI's font style from settings. """ theFont = QFont() if self.mainConf.guiFont not in self.guiFontDB.families(): if self.mainConf.osWindows and "Arial" in self.guiFontDB.families( ): # On Windows we default to Arial if possible theFont.setFamily("Arial") theFont.setPointSize(10) else: theFont = self.guiFontDB.systemFont(QFontDatabase.GeneralFont) self.mainConf.guiFont = theFont.family() self.mainConf.guiFontSize = theFont.pointSize() else: theFont.setFamily(self.mainConf.guiFont) theFont.setPointSize(self.mainConf.guiFontSize) qApp.setFont(theFont) return
def loadFontSettings(self): if self._fromTheme or \ not self._index or \ type(self._index.model()) != outlineModel or \ self._column != Outline.text.value: return opt = settings.textEditor f = QFont() f.fromString(opt["font"]) # self.setFont(f) self.setStyleSheet("""QTextEdit{{ background: {bg}; color: {foreground}; font-family: {ff}; font-size: {fs}; }} """.format( bg=opt["background"], foreground=opt["fontColor"], ff=f.family(), fs="{}pt".format(str(f.pointSize())))) cf = QTextCharFormat() # cf.setFont(f) # cf.setForeground(QColor(opt["fontColor"])) bf = QTextBlockFormat() bf.setLineHeight(opt["lineSpacing"], bf.ProportionalHeight) bf.setTextIndent(opt["tabWidth"] * 1 if opt["indent"] else 0) bf.setTopMargin(opt["spacingAbove"]) bf.setBottomMargin(opt["spacingBelow"]) self._defaultCharFormat = cf self._defaultBlockFormat = bf if self.highlighter: self.highlighter.setMisspelledColor(QColor(opt["misspelled"])) self.highlighter.setDefaultCharFormat(self._defaultCharFormat) self.highlighter.setDefaultBlockFormat(self._defaultBlockFormat)
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 updateFromSettings(self): settings = self.settings # Content s = settings["Content"] self.chkContentMore.setChecked(s["More"]) if not s["More"]: self.tblContent.item(0, 1).setCheckState(Qt.Checked if s["FolderTitle"] else Qt.Unchecked) self.tblContent.item(1, 1).setCheckState(Qt.Checked if s["TextTitle"] else Qt.Unchecked) self.tblContent.item(1, 2).setCheckState(Qt.Checked if s["TextText"] else Qt.Unchecked) else: nLevel = len(s["FolderTitle"]) for i in range(nLevel): item = self.tblContent.item(i + 2, 1) if item: item.setCheckState(Qt.Checked if s["FolderTitle"][i] else Qt.Unchecked) item = self.tblContent.item(i + 2 + nLevel, 1) if item: item.setCheckState(Qt.Checked if s["TextTitle"][i] else Qt.Unchecked) item = self.tblContent.item(i + 2 + nLevel, 2) if item: item.setCheckState(Qt.Checked if s["TextText"][i] else Qt.Unchecked) self.chkContentIgnoreCompile.setChecked(s["IgnoreCompile"]) self.chkContentParent.setChecked(s["Parent"]) self.chkContentLabels.setChecked(s["Labels"]) self.chkContentStatus.setChecked(s["Status"]) # FIXME: parent, labels, status # Separations s = settings["Separator"] for val, cmb, txt in [ ("FF", self.cmbSepFF, self.txtSepFF), ("TT", self.cmbSepTT, self.txtSepTT), ("FT", self.cmbSepFT, self.txtSepFT), ("TF", self.cmbSepTF, self.txtSepTF), ]: if s[val] == "\n": cmb.setCurrentIndex(0) else: cmb.setCurrentIndex(1) txt.setText(self._format.escapes(s[val])) # Transformations s = settings["Transform"] self.chkTransEllipse.setChecked(s["Ellipse"]) self.chkTransDash.setChecked(s["Dash"]) for val, chk, cmb, txtA, txtB in [ ("DoubleQuotes", self.chkTransDoubleQuotes, self.cmbTransDoubleQuotes, self.txtTransDoubleQuotesA, self.txtTransDoubleQuotesB), ("SingleQuote", self.chkTransSingleQuote, self.cmbTransSingleQuote, self.txtTransSingleQuoteA, self.txtTransSingleQuoteB), ]: chk.setChecked(s[val] != False) if s[val]: if cmb.findText(s[val]) != -1: cmb.setCurrentText(s[val]) else: cmb.setCurrentIndex(cmb.count() - 1) txtA.setText(s[val].split("___")[0]) txtB.setText(s[val].split("___")[1]) self.chkTransSpaces.setChecked(s["Spaces"]) for i in s["Custom"]: self.transAddTableRow(i[0], i[1], i[2], i[3]) # Preview s = settings["Preview"] f = QFont() f.fromString(s["PreviewFont"]) self.cmbPreviewFont.setCurrentFont(f) self.spnPreviewSize.setValue(f.pointSize())
def paint(self, painter, option, index): """ Public method to paint the specified list item. @param painter painter object to paint to (QPainter) @param option style option used for painting (QStyleOptionViewItem) @param index model index of the item (QModelIndex) """ opt = QStyleOptionViewItem(option) self.initStyleOption(opt, index) widget = opt.widget style = widget.style() if widget is not None else QApplication.style() height = opt.rect.height() center = height // 2 + opt.rect.top() # Prepare title font titleFont = QFont(opt.font) titleFont.setBold(True) titleFont.setPointSize(titleFont.pointSize() + 1) titleMetrics = QFontMetrics(titleFont) if Globals.isWindowsPlatform(): colorRole = QPalette.Text else: colorRole = QPalette.HighlightedText if opt.state & QStyle.State_Selected else QPalette.Text leftPos = self.__padding rightPos = opt.rect.right() - self.__padding - GreaseMonkeyConfigurationListDelegate.RemoveIconSize # Draw background style.drawPrimitive(QStyle.PE_PanelItemViewItem, opt, painter, widget) # Draw checkbox checkBoxYPos = center - GreaseMonkeyConfigurationListDelegate.CheckBoxSize // 2 opt2 = QStyleOptionViewItem(opt) if opt2.checkState == Qt.Checked: opt2.state |= QStyle.State_On else: opt2.state |= QStyle.State_Off styleCheckBoxRect = style.subElementRect(QStyle.SE_ViewItemCheckIndicator, opt2, widget) opt2.rect = QRect(leftPos, checkBoxYPos, styleCheckBoxRect.width(), styleCheckBoxRect.height()) style.drawPrimitive(QStyle.PE_IndicatorViewItemCheck, opt2, painter, widget) leftPos = opt2.rect.right() + self.__padding # Draw icon iconYPos = center - GreaseMonkeyConfigurationListDelegate.IconSize // 2 iconRect = QRect( leftPos, iconYPos, GreaseMonkeyConfigurationListDelegate.IconSize, GreaseMonkeyConfigurationListDelegate.IconSize, ) pixmap = index.data(Qt.DecorationRole).pixmap(GreaseMonkeyConfigurationListDelegate.IconSize) painter.drawPixmap(iconRect, pixmap) leftPos = iconRect.right() + self.__padding # Draw script name name = index.data(Qt.DisplayRole) leftTitleEdge = leftPos + 2 rightTitleEdge = rightPos - self.__padding leftPosForVersion = titleMetrics.width(name) + self.__padding nameRect = QRect( leftTitleEdge, opt.rect.top() + self.__padding, rightTitleEdge - leftTitleEdge, titleMetrics.height() ) painter.setFont(titleFont) style.drawItemText(painter, nameRect, Qt.AlignLeft, opt.palette, True, name, colorRole) # Draw version version = index.data(Qt.UserRole) versionRect = QRect( nameRect.x() + leftPosForVersion, nameRect.y(), rightTitleEdge - leftTitleEdge, titleMetrics.height() ) versionFont = titleFont painter.setFont(versionFont) style.drawItemText(painter, versionRect, Qt.AlignLeft, opt.palette, True, version, colorRole) # Draw description infoYPos = nameRect.bottom() + opt.fontMetrics.leading() infoRect = QRect(nameRect.x(), infoYPos, nameRect.width(), opt.fontMetrics.height()) info = opt.fontMetrics.elidedText(index.data(Qt.UserRole + 1), Qt.ElideRight, infoRect.width()) painter.setFont(opt.font) style.drawItemText(painter, infoRect, Qt.AlignLeft | Qt.TextSingleLine, opt.palette, True, info, colorRole) # Draw remove button removeIconYPos = center - GreaseMonkeyConfigurationListDelegate.RemoveIconSize // 2 removeIconRect = QRect( rightPos, removeIconYPos, GreaseMonkeyConfigurationListDelegate.RemoveIconSize, GreaseMonkeyConfigurationListDelegate.RemoveIconSize, ) painter.drawPixmap(removeIconRect, self.__removePixmap)
class CharacterWidget(QWidget): characterSelected = pyqtSignal(str) def __init__(self, parent=None): super(CharacterWidget, self).__init__(parent) self.displayFont = QFont() self.squareSize = 24 self.columns = 16 self.lastKey = -1 self.setMouseTracking(True) def updateFont(self, fontFamily): self.displayFont.setFamily(fontFamily) self.squareSize = max(24, QFontMetrics(self.displayFont).xHeight() * 3) self.adjustSize() self.update() def updateSize(self, fontSize): fontSize, _ = fontSize.toInt() self.displayFont.setPointSize(fontSize) self.squareSize = max(24, QFontMetrics(self.displayFont).xHeight() * 3) self.adjustSize() self.update() def updateStyle(self, fontStyle): fontDatabase = QFontDatabase() oldStrategy = self.displayFont.styleStrategy() self.displayFont = fontDatabase.font(self.displayFont.family(), fontStyle, self.displayFont.pointSize()) self.displayFont.setStyleStrategy(oldStrategy) self.squareSize = max(24, QFontMetrics(self.displayFont).xHeight() * 3) self.adjustSize() self.update() def updateFontMerging(self, enable): if enable: self.displayFont.setStyleStrategy(QFont.PreferDefault) else: self.displayFont.setStyleStrategy(QFont.NoFontMerging) self.adjustSize() self.update() def sizeHint(self): return QSize(self.columns * self.squareSize, (65536 / self.columns) * self.squareSize) def mouseMoveEvent(self, event): widgetPosition = self.mapFromGlobal(event.globalPos()) key = (widgetPosition.y() // self.squareSize) * self.columns + widgetPosition.x() // self.squareSize text = '<p>Character: <span style="font-size: 24pt; font-family: %s">%s</span><p>Value: 0x%x' % (self.displayFont.family(), self._chr(key), key) QToolTip.showText(event.globalPos(), text, self) def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.lastKey = (event.y() // self.squareSize) * self.columns + event.x() // self.squareSize key_ch = self._chr(self.lastKey) if unicodedata.category(key_ch) != 'Cn': self.characterSelected.emit(key_ch) self.update() else: super(CharacterWidget, self).mousePressEvent(event) def paintEvent(self, event): painter = QPainter(self) painter.fillRect(event.rect(), Qt.white) painter.setFont(self.displayFont) redrawRect = event.rect() beginRow = redrawRect.top() // self.squareSize endRow = redrawRect.bottom() // self.squareSize beginColumn = redrawRect.left() // self.squareSize endColumn = redrawRect.right() // self.squareSize painter.setPen(Qt.gray) for row in range(beginRow, endRow + 1): for column in range(beginColumn, endColumn + 1): painter.drawRect(column * self.squareSize, row * self.squareSize, self.squareSize, self.squareSize) fontMetrics = QFontMetrics(self.displayFont) painter.setPen(Qt.black) for row in range(beginRow, endRow + 1): for column in range(beginColumn, endColumn + 1): key = row * self.columns + column painter.setClipRect(column * self.squareSize, row * self.squareSize, self.squareSize, self.squareSize) if key == self.lastKey: painter.fillRect(column * self.squareSize + 1, row * self.squareSize + 1, self.squareSize, self.squareSize, Qt.red) key_ch = self._chr(key) painter.drawText(column * self.squareSize + (self.squareSize / 2) - fontMetrics.width(key_ch) / 2, row * self.squareSize + 4 + fontMetrics.ascent(), key_ch) @staticmethod def _chr(codepoint): try: # Python v2. return unichr(codepoint) except NameError: # Python v3. return chr(codepoint)
class CharMap(QWidget): """A widget displaying a table of characters.""" characterSelected = pyqtSignal(str) characterClicked = pyqtSignal(str) def __init__(self, parent=None): super(CharMap, self).__init__(parent) self._showToolTips = True self._showWhatsThis = True self._selected = -1 self._column_count = 32 self._square = 24 self._range = (0, 0) self._font = QFont() def setRange(self, first, last): self._range = (first, last) self._selected = -1 self.adjustSize() self.update() def range(self): return self._range def square(self): """Returns the width of one item (determined by font size).""" return self._square def select(self, charcode): """Selects the specified character (int or str).""" if not isinstance(charcode, int): charcode = ord(charcode) if not self._range[0] <= charcode <= self._range[1]: charcode = -1 if self._selected != charcode: self._selected = charcode self.characterSelected.emit(chr(charcode)) self.update() def character(self): """Returns the currently selected character, if any.""" if self._selected != -1: return chr(self._selected) def setDisplayFont(self, font): self._font.setFamily(font.family()) self.update() def displayFont(self): return QFont(self._font) def setDisplayFontSize(self, size): self._font.setPointSize(size) self._square = max(24, QFontMetrics(self._font).xHeight() * 3) self.adjustSize() self.update() def displayFontSize(self): return self._font.pointSize() def setDisplayFontSizeF(self, size): self._font.setPointSizeF(size) self._square = max(24, QFontMetrics(self._font).xHeight() * 3) self.adjustSize() self.update() def displayFontSizeF(self): return self._font.pointSizeF() def setColumnCount(self, count): """Sets how many columns should be used.""" count = max(1, count) self._column_count = count self.adjustSize() self.update() def columnCount(self): return self._column_count def sizeHint(self): return self.sizeForColumnCount(self._column_count) def paintEvent(self, ev): rect = ev.rect() s = self._square rows = range(rect.top() // s, rect.bottom() // s + 1) cols = range(rect.left() // s, rect.right() // s + 1) painter = QPainter(self) painter.setPen(QPen(self.palette().color(QPalette.Window))) painter.setFont(self._font) metrics = QFontMetrics(self._font) # draw characters on white tiles tile = self.palette().color(QPalette.Base) selected_tile = self.palette().color(QPalette.Highlight) selected_tile.setAlpha(96) selected_box = self.palette().color(QPalette.Highlight) text_pen = QPen(self.palette().text().color()) disabled_pen = QPen(self.palette().color(QPalette.Disabled, QPalette.Text)) selection_pen = QPen(selected_box) for row in rows: for col in cols: char = row * self._column_count + col + self._range[0] if char > self._range[1]: break printable = self.isprint(char) painter.setClipRect(col * s, row * s, s, s) if char == self._selected: painter.fillRect(col * s + 1, row * s + 1, s - 2, s - 2, selected_tile) painter.setPen(selection_pen) painter.drawRect(col * s, row * s, s - 1, s - 1) elif printable: painter.fillRect(col * s + 1, row * s + 1, s - 2, s - 2, tile) painter.setPen(text_pen if printable else disabled_pen) t = chr(char) x = col * s + s // 2 - metrics.width(t) // 2 y = row * s + 4 + metrics.ascent() painter.drawText(x, y, t) else: continue break def sizeForColumnCount(self, count): """Returns the size the widget would have in a certain column count. This can be used in e.g. a resizable scroll area. """ first, last = self._range rows = ((last - first) // count) + 1 return QSize(count, rows) * self._square def columnCountForWidth(self, width): """Returns the number of columns that would fit into the given width.""" return width // self._square def mousePressEvent(self, ev): charcode = self.charcodeAt(ev.pos()) if charcode != -1 and self.isprint(charcode): self.select(charcode) if ev.button() != Qt.RightButton: self.characterClicked.emit(chr(charcode)) def charcodeRect(self, charcode): """Returns the rectangular box around the given charcode, if any.""" if self._range[0] <= charcode <= self._range[1]: row, col = divmod(charcode - self._range[0], self._column_count) s = self._square return QRect(col * s, row * s, s, s) def charcodeAt(self, position): row = position.y() // self._square col = position.x() // self._square if col <= self._column_count: charcode = self._range[0] + row * self._column_count + col if charcode <= self._range[1]: return charcode return -1 def event(self, ev): if ev.type() == QEvent.ToolTip: if self._showToolTips: c = self.charcodeAt(ev.pos()) if c: text = self.getToolTipText(c) if text: rect = self.charcodeRect(c) QToolTip.showText(ev.globalPos(), text, self, rect) ev.accept() return True elif ev.type() == QEvent.QueryWhatsThis: if self._showWhatsThis: ev.accept() return True elif ev.type() == QEvent.WhatsThis: ev.accept() if self._showWhatsThis: c = self.charcodeAt(ev.pos()) text = self.getWhatsThisText(c) if c else None if text: QWhatsThis.showText(ev.globalPos(), text, self) else: QWhatsThis.leaveWhatsThisMode() return True return super(CharMap, self).event(ev) def getToolTipText(self, charcode): try: return unicodedata.name(chr(charcode)) except ValueError: pass def getWhatsThisText(self, charcode): try: name = unicodedata.name(chr(charcode)) except ValueError: return return whatsthis_html.format( self._font.family(), chr(charcode), name, charcode) def setShowToolTips(self, enabled): self._showToolTips = bool(enabled) def showToolTips(self): return self._showToolTips def setShowWhatsThis(self, enabled): self._showWhatsThis = bool(enabled) def showWhatsThis(self): return self._showWhatsThis def isprint(self, charcode): """Returns True if the given charcode is printable.""" return isprint(charcode)
from PyQt5.QtGui import QPixmap, QImage, QFont # from urllib.request import Request, urlopen # from urllib.error import URLError, HTTPError from vk_ui import Ui_MainWindow from vk_settings_ui import Ui_Form from add_ui import Ui_FormUrl from downloading_ui import Ui_FormDownload app = QApplication(sys.argv) image = QPixmap('./pic/111.jpg') splash = QSplashScreen(image) splash.setAttribute(QtCore.Qt.WA_DeleteOnClose) splash = QSplashScreen(image, Qt.WindowStaysOnTopHint) splash.setMask(image.mask()) font = QFont(splash.font()) font.setPointSize(font.pointSize() + 5) splash.setFont(font) splash.show() app.processEvents() # time.sleep(2) # splash.showMessage(splash.tr('Processing %1...{0}'),QtCore.Qt.AlignBottom | QtCore.Qt.AlignLeft, QtCore.Qt.white) # QtCore.QThread.msleep(1000) # QApplication.processEvents() for count in range(1, 6): # splash.showMessage(splash, str(count),QtCore.Qt.AlignBottom | QtCore.Qt.AlignLeft, QtCore.Qt.blue) splash.showMessage('Loading: ' + str(count), QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft, QtCore.Qt.white) # print(str(count)) # app.processEvents() QtCore.QThread.msleep(1000)
def __init__(self, mainWindow): QWidget.__init__(self) self.setupUi(self) self.mw = mainWindow # UI for i in range(self.lstMenu.count()): item = self.lstMenu.item(i) item.setSizeHint(QSize(item.sizeHint().width(), 42)) item.setTextAlignment(Qt.AlignCenter) self.lstMenu.setMaximumWidth(150) # General self.cmbStyle.addItems(list(QStyleFactory.keys())) self.cmbStyle.setCurrentIndex([i.lower() for i in list(QStyleFactory.keys())].index(qApp.style().objectName())) self.cmbStyle.currentIndexChanged[str].connect(self.setStyle) self.txtAutoSave.setValidator(QIntValidator(0, 999, self)) self.txtAutoSaveNoChanges.setValidator(QIntValidator(0, 999, self)) self.chkAutoSave.setChecked(settings.autoSave) self.chkAutoSaveNoChanges.setChecked(settings.autoSaveNoChanges) self.txtAutoSave.setText(str(settings.autoSaveDelay)) self.txtAutoSaveNoChanges.setText(str(settings.autoSaveNoChangesDelay)) self.chkSaveOnQuit.setChecked(settings.saveOnQuit) self.chkAutoSave.stateChanged.connect(self.saveSettingsChanged) self.chkAutoSaveNoChanges.stateChanged.connect(self.saveSettingsChanged) self.chkSaveOnQuit.stateChanged.connect(self.saveSettingsChanged) self.txtAutoSave.textEdited.connect(self.saveSettingsChanged) self.txtAutoSaveNoChanges.textEdited.connect(self.saveSettingsChanged) autoLoad, last = self.mw.welcome.getAutoLoadValues() self.chkAutoLoad.setChecked(autoLoad) self.chkAutoLoad.stateChanged.connect(self.saveSettingsChanged) dtt = [ ("t2t", self.tr("Txt2Tags"), "text-x-script"), ("html", self.tr("Rich Text (html)"), "text-html"), ("txt", self.tr("Plain Text"), "text-x-generic"), ] self.cmbDefaultTextType.clear() for t in dtt: self.cmbDefaultTextType.addItem(QIcon.fromTheme(t[2]), t[1], t[0]) i = self.cmbDefaultTextType.findData(settings.defaultTextType) if i != -1: self.cmbDefaultTextType.setCurrentIndex(i) self.cmbDefaultTextType.currentIndexChanged.connect(self.saveSettingsChanged) # Revisions opt = settings.revisions self.chkRevisionsKeep.setChecked(opt["keep"]) self.chkRevisionsKeep.stateChanged.connect(self.revisionsSettingsChanged) self.chkRevisionRemove.setChecked(opt["smartremove"]) self.chkRevisionRemove.toggled.connect(self.revisionsSettingsChanged) self.spnRevisions10Mn.setValue(60 / opt["rules"][10 * 60]) self.spnRevisions10Mn.valueChanged.connect(self.revisionsSettingsChanged) self.spnRevisionsHour.setValue(60 * 10 / opt["rules"][60 * 60]) self.spnRevisionsHour.valueChanged.connect(self.revisionsSettingsChanged) self.spnRevisionsDay.setValue(60 * 60 / opt["rules"][60 * 60 * 24]) self.spnRevisionsDay.valueChanged.connect(self.revisionsSettingsChanged) self.spnRevisionsMonth.setValue(60 * 60 * 24 / opt["rules"][60 * 60 * 24 * 30]) self.spnRevisionsMonth.valueChanged.connect(self.revisionsSettingsChanged) self.spnRevisionsEternity.setValue(60 * 60 * 24 * 7 / opt["rules"][None]) self.spnRevisionsEternity.valueChanged.connect(self.revisionsSettingsChanged) # Views self.tabViews.setCurrentIndex(0) lst = ["Nothing", "POV", "Label", "Progress", "Compile"] for cmb in self.viewSettingsDatas(): item, part = self.viewSettingsDatas()[cmb] cmb.setCurrentIndex(lst.index(settings.viewSettings[item][part])) cmb.currentIndexChanged.connect(self.viewSettingsChanged) for chk in self.outlineColumnsData(): col = self.outlineColumnsData()[chk] chk.setChecked(col in settings.outlineViewColumns) chk.stateChanged.connect(self.outlineColumnsChanged) for item, what, value in [ (self.rdoTreeItemCount, "InfoFolder", "Count"), (self.rdoTreeWC, "InfoFolder", "WC"), (self.rdoTreeProgress, "InfoFolder", "Progress"), (self.rdoTreeSummary, "InfoFolder", "Summary"), (self.rdoTreeNothing, "InfoFolder", "Nothing"), (self.rdoTreeTextWC, "InfoText", "WC"), (self.rdoTreeTextProgress, "InfoText", "Progress"), (self.rdoTreeTextSummary, "InfoText", "Summary"), (self.rdoTreeTextNothing, "InfoText", "Nothing"), ]: item.setChecked(settings.viewSettings["Tree"][what] == value) item.toggled.connect(self.treeViewSettignsChanged) self.populatesCmbBackgrounds(self.cmbCorkImage) self.setCorkImageDefault() self.updateCorkColor() self.cmbCorkImage.currentIndexChanged.connect(self.setCorkBackground) self.btnCorkColor.clicked.connect(self.setCorkColor) # Text editor opt = settings.textEditor self.setButtonColor(self.btnEditorFontColor, opt["fontColor"]) self.btnEditorFontColor.clicked.connect(self.choseEditorFontColor) self.setButtonColor(self.btnEditorMisspelledColor, opt["misspelled"]) self.btnEditorMisspelledColor.clicked.connect(self.choseEditorMisspelledColor) self.setButtonColor(self.btnEditorBackgroundColor, opt["background"]) self.btnEditorBackgroundColor.clicked.connect(self.choseEditorBackgroundColor) f = QFont() f.fromString(opt["font"]) self.cmbEditorFontFamily.setCurrentFont(f) self.cmbEditorFontFamily.currentFontChanged.connect(self.updateEditorSettings) self.spnEditorFontSize.setValue(f.pointSize()) self.spnEditorFontSize.valueChanged.connect(self.updateEditorSettings) self.cmbEditorLineSpacing.setCurrentIndex( 0 if opt["lineSpacing"] == 100 else 1 if opt["lineSpacing"] == 150 else 2 if opt["lineSpacing"] == 200 else 3) self.cmbEditorLineSpacing.currentIndexChanged.connect(self.updateEditorSettings) self.spnEditorLineSpacing.setValue(opt["lineSpacing"]) self.spnEditorLineSpacing.valueChanged.connect(self.updateEditorSettings) self.spnEditorLineSpacing.setEnabled(opt["lineSpacing"] not in [100, 150, 200]) self.spnEditorLineSpacing.valueChanged.connect(self.updateEditorSettings) self.spnEditorTabWidth.setValue(opt["tabWidth"]) self.spnEditorTabWidth.valueChanged.connect(self.updateEditorSettings) self.chkEditorIndent.setChecked(opt["indent"]) self.chkEditorIndent.stateChanged.connect(self.updateEditorSettings) self.spnEditorParaAbove.setValue(opt["spacingAbove"]) self.spnEditorParaAbove.valueChanged.connect(self.updateEditorSettings) self.spnEditorParaBelow.setValue(opt["spacingBelow"]) self.spnEditorParaAbove.valueChanged.connect(self.updateEditorSettings) # Labels self.lstLabels.setModel(self.mw.mdlLabels) self.lstLabels.setRowHidden(0, True) self.lstLabels.clicked.connect(self.updateLabelColor) self.btnLabelAdd.clicked.connect(self.addLabel) self.btnLabelRemove.clicked.connect(self.removeLabel) self.btnLabelColor.clicked.connect(self.setLabelColor) # Statuses self.lstStatus.setModel(self.mw.mdlStatus) self.lstStatus.setRowHidden(0, True) self.btnStatusAdd.clicked.connect(self.addStatus) self.btnStatusRemove.clicked.connect(self.removeStatus) # Fullscreen self._editingTheme = None self.btnThemeEditOK.setIcon(qApp.style().standardIcon(QStyle.SP_DialogApplyButton)) self.btnThemeEditOK.clicked.connect(self.saveTheme) self.btnThemeEditCancel.setIcon(qApp.style().standardIcon(QStyle.SP_DialogCancelButton)) self.btnThemeEditCancel.clicked.connect(self.cancelEdit) self.cmbThemeEdit.currentIndexChanged.connect(self.themeEditStack.setCurrentIndex) self.cmbThemeEdit.setCurrentIndex(0) self.cmbThemeEdit.currentIndexChanged.emit(0) self.themeStack.setCurrentIndex(0) self.lstThemes.currentItemChanged.connect(self.themeSelected) self.populatesThemesList() self.btnThemeAdd.clicked.connect(self.newTheme) self.btnThemeEdit.clicked.connect(self.editTheme) self.btnThemeRemove.clicked.connect(self.removeTheme)
def paint_v2(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, rect=self.mainRect): p.translate(rect.center()) p.rotate(angle) p.translate(-rect.center()) def drawRect(r): p.save() p.setBrush(Qt.gray) p.drawRect(r) p.restore() # 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.drawRect(option.rect) p.restore() # Background p.save() if settings.viewSettings["Cork"]["Background"] != "Nothing": c = colors[settings.viewSettings["Cork"]["Background"]] if c == QColor(Qt.transparent): c = QColor(Qt.white) col = mixColors(c, QColor(Qt.white), .2) backgroundColor = col p.setBrush(col) else: p.setBrush(Qt.white) backgroundColor = QColor(Qt.white) # Cache background color self.bgColors[index] = backgroundColor.name() p.setPen(Qt.NoPen) p.drawRect(self.cardRect) if item.isFolder(): itemPoly = QPolygonF([ self.topRect.topLeft(), self.topRect.topLeft() + QPoint(self.topRect.width() * .35, 0), self.cardRect.topLeft() + QPoint(self.topRect.width() * .45, 0), self.cardRect.topRight(), self.cardRect.bottomRight(), self.cardRect.bottomLeft() ]) p.drawPolygon(itemPoly) 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.drawRect(self.labelRect) w = self.labelRect.width() poly = QPolygonF([ self.labelRect.bottomLeft() + QPointF(0, 1), self.labelRect.bottomLeft() + QPointF(0, w / 2), self.labelRect.bottomLeft() + QPointF(w / 2, 1), self.labelRect.bottomRight() + QPointF(1, w / 2), self.labelRect.bottomRight() + QPointF(1, 1), ]) p.drawPolygon(poly) p.restore() if settings.viewSettings["Cork"]["Corner"] == "Nothing" or \ color == Qt.transparent: # No corner, so title can be full width self.titleRect.setRight(self.mainRect.right()) # 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() if text: p.setPen(Qt.black) textColor = QColor(Qt.black) if settings.viewSettings["Cork"]["Text"] != "Nothing": col = colors[settings.viewSettings["Cork"]["Text"]] if col == Qt.transparent: col = Qt.black # If title setting is compile, we have to hack the color # Or we won't see anything in some themes if settings.viewSettings["Cork"]["Text"] == "Compile": if item.compile() in [0, "0"]: col = mixColors(QColor(Qt.black), backgroundColor) else: col = Qt.black textColor = col p.setPen(col) f = QFont(option.font) f.setPointSize(f.pointSize() + 4) f.setBold(True) p.setFont(f) fm = QFontMetrics(f) elidedText = fm.elidedText(text, Qt.ElideRight, self.titleRect.width()) p.drawText(self.titleRect, Qt.AlignLeft | Qt.AlignVCenter, elidedText) p.restore() # One line summary background lineSummary = item.data(Outline.summarySentence) fullSummary = item.data(Outline.summaryFull) # Border if settings.viewSettings["Cork"]["Border"] != "Nothing": p.save() p.setBrush(Qt.NoBrush) pen = p.pen() pen.setWidth(2) col = colors[settings.viewSettings["Cork"]["Border"]] pen.setColor(col) p.setPen(pen) if item.isFolder(): p.drawPolygon(itemPoly) else: p.drawRect(self.cardRect) p.restore() # Draw status status = item.data(Outline.status) if status: it = mainWindow().mdlStatus.item(int(status), 0) if it != None: p.save() p.setClipRegion(QRegion(self.cardRect)) f = p.font() f.setPointSize(f.pointSize() + 12) f.setBold(True) p.setFont(f) p.setPen(QColor(Qt.red).lighter(170)) _rotate(-35, rect=self.cardRect) p.drawText(self.cardRect, Qt.AlignCenter, it.text()) p.restore() # Draw Summary # One line if lineSummary: p.save() f = QFont(option.font) f.setBold(True) p.setFont(f) p.setPen(textColor) fm = QFontMetrics(f) elidedText = fm.elidedText(lineSummary, Qt.ElideRight, self.mainLineRect.width()) p.drawText(self.mainLineRect, Qt.AlignLeft | Qt.AlignVCenter, elidedText) p.restore() # Full summary if fullSummary: p.save() p.setFont(option.font) p.setPen(textColor) p.drawText(self.mainTextRect, Qt.TextWordWrap, fullSummary) p.restore()
def loadFontSettings(self): if self._fromTheme or \ not self._index or \ type(self._index.model()) != outlineModel or \ self._column != Outline.text: return opt = settings.textEditor f = QFont() f.fromString(opt["font"]) background = (opt["background"] if not opt["backgroundTransparent"] else "transparent") foreground = opt["fontColor"] # if not opt["backgroundTransparent"] # else S.text # self.setFont(f) self.setStyleSheet("""QTextEdit{{ background: {bg}; color: {foreground}; font-family: {ff}; font-size: {fs}; margin: {mTB}px {mLR}px; {maxWidth} }} """.format( bg=background, foreground=foreground, ff=f.family(), fs="{}pt".format(str(f.pointSize())), mTB = opt["marginsTB"], mLR = opt["marginsLR"], maxWidth = "max-width: {}px;".format(opt["maxWidth"]) if opt["maxWidth"] else "", ) ) self._defaultFontSize = f.pointSize() # We set the parent background to the editor's background in case # there are margins. We check that the parent class is a QWidget because # if textEditView is used in fullScreenEditor, then we don't want to # set the background. if self.parent().__class__ == QWidget: self.parent().setStyleSheet(""" QWidget#{name}{{ background: {bg}; }}""".format( # We style by name, otherwise all inheriting widgets get the same # colored background, for example context menu. name=self.parent().objectName(), bg=background, )) cf = QTextCharFormat() # cf.setFont(f) # cf.setForeground(QColor(opt["fontColor"])) self.setCursorWidth(opt["cursorWidth"]) bf = QTextBlockFormat() bf.setLineHeight(opt["lineSpacing"], bf.ProportionalHeight) bf.setTextIndent(opt["tabWidth"] * 1 if opt["indent"] else 0) bf.setTopMargin(opt["spacingAbove"]) bf.setBottomMargin(opt["spacingBelow"]) bf.setAlignment(Qt.AlignLeft if opt["textAlignment"] == 0 else Qt.AlignCenter if opt["textAlignment"] == 1 else Qt.AlignRight if opt["textAlignment"] == 2 else Qt.AlignJustify) self._defaultCharFormat = cf self._defaultBlockFormat = bf if self.highlighter: self.highlighter.updateColorScheme() self.highlighter.setMisspelledColor(QColor(opt["misspelled"])) self.highlighter.setDefaultCharFormat(self._defaultCharFormat) self.highlighter.setDefaultBlockFormat(self._defaultBlockFormat)
def __init__(self, mainWindow): QWidget.__init__(self) self.setupUi(self) self.mw = mainWindow # UI for l in [self.lblTitleGeneral, self.lblTitleGeneral_2, self.lblTitleViews, self.lblTitleLabels, self.lblTitleStatus, self.lblTitleFullscreen, ]: l.setStyleSheet(S.titleLabelSS()) icons = [QIcon.fromTheme("configure"), QIcon.fromTheme("history-view"), QIcon.fromTheme("gnome-settings"), themeIcon("label"), themeIcon("status"), QIcon.fromTheme("preferences-desktop-theme") ] for i in range(self.lstMenu.count()): item = self.lstMenu.item(i) item.setSizeHint(QSize(item.sizeHint().width(), 42)) item.setTextAlignment(Qt.AlignCenter) if icons[i]: item.setIcon(icons[i]) self.lstMenu.setMaximumWidth(140) self.lstMenu.setMinimumWidth(140) # General self.cmbStyle.addItems(list(QStyleFactory.keys())) self.cmbStyle.setCurrentIndex( [i.lower() for i in list(QStyleFactory.keys())] .index(qApp.style().objectName())) self.cmbStyle.currentIndexChanged[str].connect(self.setStyle) self.cmbTranslation.clear() tr = OrderedDict() tr["English"] = "" tr["Arabic (Saudi Arabia)"] = "manuskript_ar_SA.qm" tr["Deutsch"] = "manuskript_de.qm" tr["Español"] = "manuskript_es.qm" tr["Français"] = "manuskript_fr.qm" tr["Hungarian"] = "manuskript_hu.qm" tr["Indonesian"] = "manuskript_id.qm" tr["Italian"] = "manuskript_it.qm" tr["Norwegian Bokmål"] = "manuskript_nb_NO.qm" tr["Dutch"] = "manuskript_nl.qm" tr["Polish"] = "manuskript_pl.qm" tr["Portuguese (Brazil)"] = "manuskript_pt_BR.qm" tr["Portuguese (Portugal)"] = "manuskript_pt_PT.qm" tr["Russian"] = "manuskript_ru.qm" tr["Svenska"] = "manuskript_sv.qm" tr["Ukranian"] = "manuskript_uk.qm" tr["Chinese (Simplified)"] = "manuskript_zh_CN.qm" self.translations = tr for name in tr: self.cmbTranslation.addItem(name, tr[name]) sttgs = QSettings(qApp.organizationName(), qApp.applicationName()) if (sttgs.contains("applicationTranslation") and sttgs.value("applicationTranslation") in tr.values()): # Sets the correct translation self.cmbTranslation.setCurrentText( [i for i in tr if tr[i] == sttgs.value("applicationTranslation")][0]) self.cmbTranslation.currentIndexChanged.connect(self.setTranslation) f = qApp.font() self.spnGeneralFontSize.setValue(f.pointSize()) self.spnGeneralFontSize.valueChanged.connect(self.setAppFontSize) self.txtAutoSave.setValidator(QIntValidator(0, 999, self)) self.txtAutoSaveNoChanges.setValidator(QIntValidator(0, 999, self)) self.chkAutoSave.setChecked(settings.autoSave) self.chkAutoSaveNoChanges.setChecked(settings.autoSaveNoChanges) self.txtAutoSave.setText(str(settings.autoSaveDelay)) self.txtAutoSaveNoChanges.setText(str(settings.autoSaveNoChangesDelay)) self.chkSaveOnQuit.setChecked(settings.saveOnQuit) self.chkSaveToZip.setChecked(settings.saveToZip) self.chkAutoSave.stateChanged.connect(self.saveSettingsChanged) self.chkAutoSaveNoChanges.stateChanged.connect(self.saveSettingsChanged) self.chkSaveOnQuit.stateChanged.connect(self.saveSettingsChanged) self.chkSaveToZip.stateChanged.connect(self.saveSettingsChanged) self.txtAutoSave.textEdited.connect(self.saveSettingsChanged) self.txtAutoSaveNoChanges.textEdited.connect(self.saveSettingsChanged) autoLoad, last = self.mw.welcome.getAutoLoadValues() self.chkAutoLoad.setChecked(autoLoad) self.chkAutoLoad.stateChanged.connect(self.saveSettingsChanged) # Revisions opt = settings.revisions self.chkRevisionsKeep.setChecked(opt["keep"]) self.chkRevisionsKeep.stateChanged.connect(self.revisionsSettingsChanged) self.chkRevisionRemove.setChecked(opt["smartremove"]) self.chkRevisionRemove.toggled.connect(self.revisionsSettingsChanged) self.spnRevisions10Mn.setValue(60 / opt["rules"][10 * 60]) self.spnRevisions10Mn.valueChanged.connect(self.revisionsSettingsChanged) self.spnRevisionsHour.setValue(60 * 10 / opt["rules"][60 * 60]) self.spnRevisionsHour.valueChanged.connect(self.revisionsSettingsChanged) self.spnRevisionsDay.setValue(60 * 60 / opt["rules"][60 * 60 * 24]) self.spnRevisionsDay.valueChanged.connect(self.revisionsSettingsChanged) self.spnRevisionsMonth.setValue(60 * 60 * 24 / opt["rules"][60 * 60 * 24 * 30]) self.spnRevisionsMonth.valueChanged.connect(self.revisionsSettingsChanged) self.spnRevisionsEternity.setValue(60 * 60 * 24 * 7 / opt["rules"][None]) self.spnRevisionsEternity.valueChanged.connect(self.revisionsSettingsChanged) # Views self.tabViews.setCurrentIndex(0) lst = ["Nothing", "POV", "Label", "Progress", "Compile"] for cmb in self.viewSettingsDatas(): item, part = self.viewSettingsDatas()[cmb] cmb.setCurrentIndex(lst.index(settings.viewSettings[item][part])) cmb.currentIndexChanged.connect(self.viewSettingsChanged) for chk in self.outlineColumnsData(): col = self.outlineColumnsData()[chk] chk.setChecked(col in settings.outlineViewColumns) chk.stateChanged.connect(self.outlineColumnsChanged) self.chkOutlinePOV.setVisible(settings.viewMode != "simple") # Hides checkbox if non-fiction view mode for item, what, value in [ (self.rdoTreeItemCount, "InfoFolder", "Count"), (self.rdoTreeWC, "InfoFolder", "WC"), (self.rdoTreeProgress, "InfoFolder", "Progress"), (self.rdoTreeSummary, "InfoFolder", "Summary"), (self.rdoTreeNothing, "InfoFolder", "Nothing"), (self.rdoTreeTextWC, "InfoText", "WC"), (self.rdoTreeTextProgress, "InfoText", "Progress"), (self.rdoTreeTextSummary, "InfoText", "Summary"), (self.rdoTreeTextNothing, "InfoText", "Nothing"), ]: item.setChecked(settings.viewSettings["Tree"][what] == value) item.toggled.connect(self.treeViewSettignsChanged) self.sldTreeIconSize.valueChanged.connect(self.treeViewSettignsChanged) self.sldTreeIconSize.valueChanged.connect( lambda v: self.lblTreeIconSize.setText("{}x{}".format(v, v))) self.sldTreeIconSize.setValue(settings.viewSettings["Tree"]["iconSize"]) self.rdoCorkOldStyle.setChecked(settings.corkStyle == "old") self.rdoCorkNewStyle.setChecked(settings.corkStyle == "new") self.rdoCorkNewStyle.toggled.connect(self.setCorkStyle) self.rdoCorkOldStyle.toggled.connect(self.setCorkStyle) self.populatesCmbBackgrounds(self.cmbCorkImage) self.setCorkImageDefault() self.updateCorkColor() self.cmbCorkImage.currentIndexChanged.connect(self.setCorkBackground) self.btnCorkColor.clicked.connect(self.setCorkColor) # Text editor opt = settings.textEditor # Font self.setButtonColor(self.btnEditorFontColor, opt["fontColor"]) self.btnEditorFontColor.clicked.connect(self.choseEditorFontColor) self.setButtonColor(self.btnEditorMisspelledColor, opt["misspelled"]) self.btnEditorMisspelledColor.clicked.connect(self.choseEditorMisspelledColor) self.setButtonColor(self.btnEditorBackgroundColor, opt["background"]) self.btnEditorBackgroundColor.clicked.connect(self.choseEditorBackgroundColor) self.chkEditorBackgroundTransparent.setChecked(opt["backgroundTransparent"]) self.chkEditorBackgroundTransparent.stateChanged.connect(self.updateEditorSettings) self.btnEditorColorDefault.clicked.connect(self.restoreEditorColors) f = QFont() f.fromString(opt["font"]) self.cmbEditorFontFamily.setCurrentFont(f) self.cmbEditorFontFamily.currentFontChanged.connect(self.updateEditorSettings) self.spnEditorFontSize.setValue(f.pointSize()) self.spnEditorFontSize.valueChanged.connect(self.updateEditorSettings) # Cursor self.chkEditorCursorWidth.setChecked(opt["cursorWidth"] != 1) self.chkEditorCursorWidth.stateChanged.connect(self.updateEditorSettings) self.spnEditorCursorWidth.setValue(opt["cursorWidth"] if opt["cursorWidth"] != 1 else 9) self.spnEditorCursorWidth.valueChanged.connect(self.updateEditorSettings) self.spnEditorCursorWidth.setEnabled(opt["cursorWidth"] != 1) self.chkEditorNoBlinking.setChecked(opt["cursorNotBlinking"]) self.chkEditorNoBlinking.stateChanged.connect(self.setApplicationCursorBlinking) self.chkEditorTypeWriterMode.setChecked(opt["alwaysCenter"]) self.chkEditorTypeWriterMode.stateChanged.connect(self.updateEditorSettings) self.cmbEditorFocusMode.setCurrentIndex( 0 if not opt["focusMode"] else 1 if opt["focusMode"] == "sentence" else 2 if opt["focusMode"] == "line" else 3) self.cmbEditorFocusMode.currentIndexChanged.connect(self.updateEditorSettings) # Text areas self.chkEditorMaxWidth.setChecked(opt["maxWidth"] != 0) self.chkEditorMaxWidth.stateChanged.connect(self.updateEditorSettings) self.spnEditorMaxWidth.setEnabled(opt["maxWidth"] != 0) self.spnEditorMaxWidth.setValue(500 if opt["maxWidth"] == 0 else opt["maxWidth"]) self.spnEditorMaxWidth.valueChanged.connect(self.updateEditorSettings) self.spnEditorMarginsLR.setValue(opt["marginsLR"]) self.spnEditorMarginsLR.valueChanged.connect(self.updateEditorSettings) self.spnEditorMarginsTB.setValue(opt["marginsTB"]) self.spnEditorMarginsTB.valueChanged.connect(self.updateEditorSettings) # Paragraphs self.cmbEditorAlignment.setCurrentIndex(opt["textAlignment"]) self.cmbEditorAlignment.currentIndexChanged.connect(self.updateEditorSettings) self.cmbEditorLineSpacing.setCurrentIndex( 0 if opt["lineSpacing"] == 100 else 1 if opt["lineSpacing"] == 150 else 2 if opt["lineSpacing"] == 200 else 3) self.cmbEditorLineSpacing.currentIndexChanged.connect(self.updateEditorSettings) self.spnEditorLineSpacing.setValue(opt["lineSpacing"]) self.spnEditorLineSpacing.valueChanged.connect(self.updateEditorSettings) self.spnEditorLineSpacing.setEnabled(opt["lineSpacing"] not in [100, 150, 200]) self.spnEditorLineSpacing.valueChanged.connect(self.updateEditorSettings) self.spnEditorTabWidth.setValue(opt["tabWidth"]) self.spnEditorTabWidth.valueChanged.connect(self.updateEditorSettings) self.chkEditorIndent.setChecked(opt["indent"]) self.chkEditorIndent.stateChanged.connect(self.updateEditorSettings) self.spnEditorParaAbove.setValue(opt["spacingAbove"]) self.spnEditorParaAbove.valueChanged.connect(self.updateEditorSettings) self.spnEditorParaBelow.setValue(opt["spacingBelow"]) self.spnEditorParaBelow.valueChanged.connect(self.updateEditorSettings) self.timerUpdateWidgets = QTimer() self.timerUpdateWidgets.setSingleShot(True) self.timerUpdateWidgets.setInterval(250) self.timerUpdateWidgets.timeout.connect(self.updateAllWidgets) # Labels self.lstLabels.setModel(self.mw.mdlLabels) self.lstLabels.setRowHidden(0, True) self.lstLabels.clicked.connect(self.updateLabelColor) self.btnLabelAdd.clicked.connect(self.addLabel) self.btnLabelRemove.clicked.connect(self.removeLabel) self.btnLabelColor.clicked.connect(self.setLabelColor) # Statuses self.lstStatus.setModel(self.mw.mdlStatus) self.lstStatus.setRowHidden(0, True) self.btnStatusAdd.clicked.connect(self.addStatus) self.btnStatusRemove.clicked.connect(self.removeStatus) # Fullscreen self._editingTheme = None self.btnThemeEditOK.setIcon(qApp.style().standardIcon(QStyle.SP_DialogApplyButton)) self.btnThemeEditOK.clicked.connect(self.saveTheme) self.btnThemeEditCancel.setIcon(qApp.style().standardIcon(QStyle.SP_DialogCancelButton)) self.btnThemeEditCancel.clicked.connect(self.cancelEdit) self.cmbThemeEdit.currentIndexChanged.connect(self.themeEditStack.setCurrentIndex) self.cmbThemeEdit.setCurrentIndex(0) self.cmbThemeEdit.currentIndexChanged.emit(0) self.themeStack.setCurrentIndex(0) self.lstThemes.currentItemChanged.connect(self.themeSelected) self.populatesThemesList() self.btnThemeAdd.clicked.connect(self.newTheme) self.btnThemeEdit.clicked.connect(self.editTheme) self.btnThemeRemove.clicked.connect(self.removeTheme) self.timerUpdateFSPreview = QTimer() self.timerUpdateFSPreview.setSingleShot(True) self.timerUpdateFSPreview.setInterval(250) self.timerUpdateFSPreview.timeout.connect(self.updatePreview)