def set_gui(self, qfont: QFont): self.setText(qfont.family() + " " + _format_font_size(qfont.pointSizeF())) preview_font = QFont(qfont) preview_font.setPointSizeF(self.font().pointSizeF()) self.setFont(preview_font)
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 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 __getattribute__(self, option): value = object.__getattribute__(self, option) # Choose a font just-in-time, because when the settings are # loaded it is too early to work. if option == 'font' and not value.family(): value = QFont() if option == 'editorFont' and not value.family(): value = chooseMonospaceFont() return value
def addDiplomacyLabels(self): ''' Displays diplomatic labels for every player. ''' y = 100 font = QFont() font.setPointSize(17) self.diploLbls = [] for player in self.game.players: lbl = DiploLabel(player.name, self) lbl.move(1230, y) color = player.color lbl.setStyleSheet("QWidget { color: %s }" % QColor(*color).name()) lbl.setFont(QFont(font.family(), 16, 200, True)) self.diploLbls.append(lbl) y = y + 50 diplomacy = QLabel("Diplomacy", self) diplomacy.move(1230, 50) diplomacy.setFont(QFont(font.family(), 16, 200, True))
def __getattribute__(self, option): value = object.__getattribute__(self, option) # Choose a font just-in-time, because when the settings are # loaded it is too early to work. if option == 'font' and not value.family(): value = QFont() if option == 'editorFont' and not value.family(): value = QFontDatabase.systemFont( QFontDatabase.SystemFont.FixedFont) return value
def slot_font_current_style(self): index = self.ACBFStyleClass.currentIndex() if index.isValid(): item = self.ACBFStylesModel.item(index.row()) font = QFont(self.ACBFfontCombo.currentFont()) item.setData(font.family(), role=Qt.UserRole + 1) item.setData(self.ACBFdefaultFont.currentText(), role=Qt.UserRole + 2) item.setData(self.ACBFBold.isChecked(), role=Qt.UserRole + 3) item.setData(self.ACBFItal.isChecked(), role=Qt.UserRole + 4) self.ACBFStylesModel.setItem(index.row(), item)
def setDefaultFont(self, font: QFont): super(NewLexer, self).setDefaultFont(font) m = 0 for v in lexer.__bases__[-1].__dict__.values(): if type(v) == int and v > m: m = v for i in range(m): style_font: QFont = self.font(i) style_font.setFamily(font.family()) style_font.setPointSizeF(font.pointSizeF()) self.setFont(style_font, i)
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 render__label_qfont(self, qfont: QFont): self.cfg.render.label_font = attr.evolve( self.cfg.render.label_font, # Font file selection family=qfont.family(), bold=qfont.bold(), italic=qfont.italic(), # Font size size=qfont.pointSizeF(), # QFont implementation details toString=qfont.toString(), )
def __init__(self, text='', font_string=None, margins: Margins = None): super().__init__(margins) self.text = text if font_string is None: font = QFont() font.setStyleHint(QFont.Helvetica) font.setFamily('Helvetica Neue') # font.Helvetica print('Default font:', font.family(), font.families(), font.toString()) font.setPixelSize(USABLE_HEIGHT) self.font_string = font.toString() else: self.font_string = font_string
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 __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 basic_font_metrics(self, font: QFont) -> BasicFontMetrics: """ Calculates some commonly needed font metrics and returns them in a BasicFontMetrics tuple. """ qMetric = QFontMetrics(font) info = BasicFontMetrics.make([ font.pointSizeF(), qMetric.height(), qMetric.ascent(), qMetric.boundingRect("N").height(), qMetric.boundingRect("N").width(), ]) LOG.diagnostic("GUI Font Family: %s" % font.family()) LOG.diagnostic("GUI Font Point Size: %.2f" % info.points) LOG.diagnostic("GUI Font Pixel Size: %d" % info.pixels) LOG.diagnostic("GUI Base Icon Size: %d" % info.icon_size) LOG.diagnostic("Text 'N' Height: %d" % info.n_height) LOG.diagnostic("Text 'N' Width: %d" % info.n_width) return info
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 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)
class Form(QWidget): """ Classe représentant le formulaire complet. """ def __init__(self): """ Constructeur du formulaire """ super().__init__() self.files = [] self.border_color = QColor(0, 0, 0) self.text_color = QColor(0, 0, 0) self.border_width = 1 self.font_editor = None self.url_watermark = "" try: parameters_file = open("parameters.json", 'r') self.parameters = process_json(parameters_file) parameters_file.close() except IOError: self.parameters = {} # En cas de souci print(self.parameters) self.dest = "" self.run_main() def show_files_dialog(self): """ Affichage de la fenêtre de sélection des photos à traiter """ file_dialog = QFileDialog().getOpenFileNames(self, "Choisir des images",\ "", "Photos (*.jpg *.png *.gif)") self.files = file_dialog[0] self.line_img.setText(pretty_list(file_dialog[0])) def show_file_dialog(self): """ Affichage de la fenêtre de sélection du watermark """ file_dialog = QFileDialog().getOpenFileName(self, "Choisir une image",\ "", "Photos (*.jpg *.png *.gif)") self.url_watermark = file_dialog[0] self.line_watermark.setText(file_dialog[0]) def show_directory_dialog(self): """ Affichage de la fenêtre de sélection des photos à traiter """ directory_dialog = QFileDialog().getExistingDirectory( self, "Sélectionner", "", QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks) self.dest = directory_dialog self.line_dest.setText(directory_dialog) def show_bordercolor_dialog(self): """ Affichage de la fenêtre de sélection de la couleur de bordure """ self.border_color = QColorDialog().getColor() if self.border_color.isValid(): self.color_btn.setStyleSheet("QWidget { background-color: %s }"\ % self.border_color.name()) def show_textcolor_dialog(self): """ Affichage de la fenêtre de sélection de la couleur du texte """ self.text_color = QColorDialog().getColor() if self.text_color.isValid(): self.color_btn_txt.setStyleSheet("QWidget { background-color: %s }"\ % self.text_color.name()) def show_font_dialog(self): """ Affichage de la fenêtre de mise en forme du texte """ if self.font_editor is not None: self.font_editor, valid_load = QFontDialog( self.font_editor).getFont() else: self.font_editor, valid_load = QFontDialog().getFont() if valid_load: self.font_label.setText(self.font_editor.family()) self.font_label.setFont(self.font_editor) def disable_border(self): """ Choisit ou non de rendre inactif la partie "choix de bordure" """ if self.set_border.isChecked(): self.border_width.setDisabled(False) self.color_btn.setDisabled(False) else: self.border_width.setDisabled(True) self.color_btn.setDisabled(True) def disable_redim(self): """ Choisit ou non de rendre inactif la partie "redimensionnement" """ if self.set_redim.isChecked(): self.width.setDisabled(False) self.height.setDisabled(False) else: self.width.setDisabled(True) self.height.setDisabled(True) def disable_copyright(self): """ Choisit ou non de rendre inactif la partie "copyright" """ if self.set_copyright.isChecked(): self.text_copyright.setDisabled(False) self.font_button.setDisabled(False) self.color_btn_txt.setDisabled(False) self.comboh_text.setDisabled(False) self.combov_text.setDisabled(False) else: self.text_copyright.setDisabled(True) self.font_button.setDisabled(True) self.color_btn_txt.setDisabled(True) self.comboh_text.setDisabled(True) self.combov_text.setDisabled(True) def disable_watermark(self): """ Choisit ou non de rendre inactif la partie "watermark" """ if self.set_watermark.isChecked(): self.comboh_watermark.setDisabled(False) self.combov_watermark.setDisabled(False) self.line_watermark.setDisabled(False) self.browse_watermark_button.setDisabled(False) else: self.comboh_watermark.setDisabled(True) self.combov_watermark.setDisabled(True) self.line_watermark.setDisabled(True) self.browse_watermark_button.setDisabled(True) def process_form(self): """ Effectue le chargement des données du formulaire puis l'exécution du traitement par lot """ if not self.files: errorbox = QMessageBox() errorbox.setText("Aucune photo sélectionnée !") errorbox.setWindowTitle("Erreur") errorbox.exec_() return if self.dest == "": errorbox = QMessageBox() errorbox.setText( "Merci de sélectionner un dossier d'enregistrement !") errorbox.setWindowTitle("Erreur") errorbox.exec_() return if self.set_border.isChecked(): self.parameters["border"] = {} self.parameters["border"]["color"] = self.border_color.name() self.parameters["border"]["width"] = int(self.border_width.value()) else: if "border" in self.parameters: del self.parameters["border"] if self.set_redim.isChecked(): self.parameters["size"] = [self.width.value(), self.height.value()] else: if "size" in self.parameters: del self.parameters["size"] if self.set_copyright.isChecked(): self.parameters["copyright"] = {} self.parameters["copyright"]["text"] = self.text_copyright.text() self.parameters["copyright"]["font"] = [ self.font_editor.family(), self.font_editor.pointSize() ] # Spécification des positionnements self.parameters["copyright"]["coords"] = [None, None] if self.comboh_text.currentText() == "À gauche": self.parameters["copyright"]["coords"][0] = "gauche" elif self.comboh_text.currentText() == "Centré": self.parameters["copyright"]["coords"][0] = "centre" else: self.parameters["copyright"]["coords"][0] = "droite" if self.combov_text.currentText() == "En haut": self.parameters["copyright"]["coords"][1] = "haut" elif self.combov_text.currentText() == "Centré": self.parameters["copyright"]["coords"][1] = "centre" else: self.parameters["copyright"]["coords"][1] = "bas" self.parameters["copyright"]["color"] = self.text_color.name() else: if "copyright" in self.parameters: del self.parameters["copyright"] if self.set_watermark.isChecked(): self.parameters["watermark"] = {} self.parameters["watermark"]["url"] = self.url_watermark # Spécification des positionnements self.parameters["watermark"]["coords"] = [None, None] if self.comboh_watermark.currentText() == "À gauche": self.parameters["watermark"]["coords"][0] = "gauche" elif self.comboh_watermark.currentText() == "Centré": self.parameters["watermark"]["coords"][0] = "centre" else: self.parameters["watermark"]["coords"][0] = "droite" if self.combov_watermark.currentText() == "En haut": self.parameters["watermark"]["coords"][1] = "haut" elif self.combov_watermark.currentText() == "Centré": self.parameters["watermark"]["coords"][1] = "centre" else: self.parameters["watermark"]["coords"][1] = "bas" else: if "watermark" in self.parameters: del self.parameters["watermark"] # Enregistrement des paramètres pour une prochaine exécution with open("parameters.json", "w") as parameters_file: parameters_file.write(self.get_parameters_json()) # Traitement par lot result = batch_processing(self.files, self.parameters, self.dest) msgbox = QMessageBox() msgbox.setText(result) msgbox.setWindowTitle("Traitement par lot terminé") msgbox.exec_() def run_main(self): """ Construit l'ensemble du formulaire """ main_layout = QVBoxLayout() form_layout = QFormLayout() file_widget = QWidget() hbox_img_files = QHBoxLayout() hbox_img_files.addWidget(QLabel("Photos :")) self.line_img = QLineEdit() self.line_img.setReadOnly(True) browse_button = QPushButton("&Parcourir...") hbox_img_files.addWidget(self.line_img) hbox_img_files.addWidget(browse_button) browse_button.clicked.connect(self.show_files_dialog) file_widget.setLayout(hbox_img_files) form_layout.addRow(file_widget) separateur1 = QFrame() separateur1.setFrameStyle(QFrame.HLine | QFrame.Raised) form_layout.addRow(separateur1) ## REDIMENSIONNEMENT self.set_redim = QCheckBox() self.set_redim.stateChanged.connect(self.disable_redim) form_layout.addRow("&Redimensionner :", self.set_redim) self.width = QSpinBox() self.width.setRange(1, 50000) self.width.setSuffix(" px") self.height = QSpinBox() self.height.setRange(1, 50000) self.height.setSuffix(" px") self.width.setDisabled(True) self.height.setDisabled(True) form_layout.addRow("&Nouvelle largeur (format \"paysage\") :", self.width) form_layout.addRow("N&ouvelle hauteur (format \"portrait\") :", self.height) if "size" in self.parameters: self.set_redim.setChecked(2) self.disable_redim() if self.parameters["size"] is not None and len( self.parameters["size"]) == 2: self.width.setValue(int(self.parameters["size"][0])) self.height.setValue(int(self.parameters["size"][1])) ## BORDURES separateur2 = QFrame() separateur2.setFrameStyle(QFrame.HLine | QFrame.Raised) form_layout.addRow(separateur2) self.set_border = QCheckBox() self.set_border.stateChanged.connect(self.disable_border) form_layout.addRow("&Ajouter une bordure :", self.set_border) self.border_width = QSpinBox() self.border_width.setMinimum(1) self.border_width.setSuffix(" px") form_layout.addRow("&Taille de la bordure :", self.border_width) self.color_btn = QPushButton() self.color_btn.clicked.connect(self.show_bordercolor_dialog) self.color_btn.setStyleSheet("QWidget { background-color: %s }" % self.border_color.name()) self.border_width.setDisabled(True) self.color_btn.setDisabled(True) form_layout.addRow("&Couleur de la bordure :", self.color_btn) if "border" in self.parameters: self.set_border.setChecked(2) self.disable_border() if "width" in self.parameters["border"]: self.border_width.setValue( int(self.parameters["border"]["width"])) if "color" in self.parameters["border"]: self.color_btn.setStyleSheet( "QWidget { background-color: %s }" % self.parameters["border"]["color"]) self.border_color = QColor(self.parameters["border"]["color"]) ## COPYRIGHT separateur3 = QFrame() separateur3.setFrameStyle(QFrame.HLine | QFrame.Raised) form_layout.addRow(separateur3) self.set_copyright = QCheckBox() self.set_copyright.stateChanged.connect(self.disable_copyright) form_layout.addRow("&Ajouter un copyright :", self.set_copyright) self.text_copyright = QLineEdit() form_layout.addRow("&Texte :", self.text_copyright) self.text_copyright.setDisabled(True) font_widget = QWidget() hbox_font = QHBoxLayout() hbox_font.addWidget(QLabel("Mise en forme :")) self.font_label = QLabel("Pas de mise en forme") self.font_button = QPushButton("Édition") hbox_font.addWidget(self.font_label) hbox_font.addWidget(self.font_button) self.font_button.clicked.connect(self.show_font_dialog) font_widget.setLayout(hbox_font) self.font_button.setDisabled(True) form_layout.addRow(font_widget) self.color_btn_txt = QPushButton() self.color_btn_txt.clicked.connect(self.show_textcolor_dialog) self.color_btn_txt.setStyleSheet("QWidget { background-color: %s }" % self.text_color.name()) self.color_btn_txt.setDisabled(True) form_layout.addRow("&Couleur du texte :", self.color_btn_txt) self.comboh_text = QComboBox() self.comboh_text.addItem("À gauche") self.comboh_text.addItem("Centré") self.comboh_text.addItem("À droite") self.comboh_text.setDisabled(True) form_layout.addRow("&Positionnement horizontal :", self.comboh_text) self.combov_text = QComboBox() self.combov_text.addItem("En haut") self.combov_text.addItem("Centré") self.combov_text.addItem("En bas") self.combov_text.setDisabled(True) form_layout.addRow("&Positionnement vertical :", self.combov_text) if "copyright" in self.parameters: self.set_copyright.setChecked(2) self.disable_copyright() if "text" in self.parameters["copyright"]: self.text_copyright.setText( self.parameters["copyright"]["text"]) if "color" in self.parameters["copyright"]: self.color_btn_txt.setStyleSheet( "QWidget { background-color: %s }" % self.parameters["copyright"]["color"]) self.text_color = QColor(self.parameters["copyright"]["color"]) if "font" in self.parameters["copyright"]: self.font_editor = QFont( self.parameters["copyright"]["font"][0], self.parameters["copyright"]["font"][1]) self.font_label.setText(self.font_editor.family()) self.font_label.setFont(self.font_editor) if "coords" in self.parameters["copyright"]: if self.parameters["copyright"]["coords"][0] == "gauche": self.comboh_text.setCurrentIndex(0) elif self.parameters["copyright"]["coords"][0] == "centre": self.comboh_text.setCurrentIndex(1) elif self.parameters["copyright"]["coords"][0] == "droite": self.comboh_text.setCurrentIndex(2) if self.parameters["copyright"]["coords"][1] == "haut": self.combov_text.setCurrentIndex(0) elif self.parameters["copyright"]["coords"][1] == "centre": self.combov_text.setCurrentIndex(1) elif self.parameters["copyright"]["coords"][1] == "bas": self.combov_text.setCurrentIndex(2) ## AJOUTER WATERMARK separateur4 = QFrame() separateur4.setFrameStyle(QFrame.HLine | QFrame.Raised) form_layout.addRow(separateur4) self.set_watermark = QCheckBox() self.set_watermark.stateChanged.connect(self.disable_watermark) form_layout.addRow("&Ajouter un watermark :", self.set_watermark) watermark_widget = QWidget() hbox_img_watermark = QHBoxLayout() hbox_img_watermark.addWidget(QLabel("Watermark :")) self.line_watermark = QLineEdit() self.line_watermark.setReadOnly(True) self.browse_watermark_button = QPushButton("&Parcourir...") hbox_img_watermark.addWidget(self.line_watermark) hbox_img_watermark.addWidget(self.browse_watermark_button) self.browse_watermark_button.clicked.connect(self.show_file_dialog) watermark_widget.setLayout(hbox_img_watermark) self.line_watermark.setDisabled(True) self.browse_watermark_button.setDisabled(True) form_layout.addRow(watermark_widget) self.comboh_watermark = QComboBox() self.comboh_watermark.addItem("À gauche") self.comboh_watermark.addItem("Centré") self.comboh_watermark.addItem("À droite") self.comboh_watermark.setDisabled(True) form_layout.addRow("&Positionnement horizontal :", self.comboh_watermark) self.combov_watermark = QComboBox() self.combov_watermark.addItem("En haut") self.combov_watermark.addItem("Centré") self.combov_watermark.addItem("En bas") self.combov_watermark.setDisabled(True) form_layout.addRow("&Positionnement vertical :", self.combov_watermark) if "watermark" in self.parameters: self.set_watermark.setChecked(2) self.disable_watermark() if "url" in self.parameters["watermark"]: self.line_watermark.setText( self.parameters["watermark"]["url"]) self.url_watermark = self.parameters["watermark"]["url"] if "coords" in self.parameters["watermark"]: if self.parameters["watermark"]["coords"][0] == "gauche": self.comboh_watermark.setCurrentIndex(0) elif self.parameters["watermark"]["coords"][0] == "centre": self.comboh_watermark.setCurrentIndex(1) elif self.parameters["watermark"]["coords"][0] == "droite": self.comboh_watermark.setCurrentIndex(2) if self.parameters["watermark"]["coords"][1] == "haut": self.combov_watermark.setCurrentIndex(0) elif self.parameters["watermark"]["coords"][1] == "centre": self.combov_watermark.setCurrentIndex(1) elif self.parameters["watermark"]["coords"][1] == "bas": self.combov_watermark.setCurrentIndex(2) ## DOSSIER DESTINATION separateur5 = QFrame() separateur5.setFrameStyle(QFrame.HLine | QFrame.Raised) form_layout.addRow(separateur5) dest_widget = QWidget() hbox_dest = QHBoxLayout() hbox_dest.addWidget(QLabel("Dossier d'enregistrement :")) self.line_dest = QLineEdit() self.line_dest.setReadOnly(True) browse_dest_button = QPushButton("P&arcourir...") hbox_dest.addWidget(self.line_dest) hbox_dest.addWidget(browse_dest_button) browse_dest_button.clicked.connect(self.show_directory_dialog) dest_widget.setLayout(hbox_dest) form_layout.addRow(dest_widget) main_layout.addLayout(form_layout) btn_valider = QPushButton("&Exécuter les tâches") btn_valider.clicked.connect(self.process_form) main_layout.addStretch(1) main_layout.addWidget(btn_valider) self.setLayout(main_layout) def get_parameters_json(self): """ Retourne les paramètres du traitement par lot au format JSON. """ return json.dumps(self.parameters, sort_keys=True, indent=4)
class ReTextWindow(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.initConfig() self.resize(950, 700) screenRect = QDesktopWidget().screenGeometry() if globalSettings.windowGeometry: self.restoreGeometry(globalSettings.windowGeometry) else: self.move((screenRect.width()-self.width())/2, (screenRect.height()-self.height())/2) if not screenRect.contains(self.geometry()): self.showMaximized() if globalSettings.iconTheme: QIcon.setThemeName(globalSettings.iconTheme) if QFile.exists(icon_path+'retext.png'): self.setWindowIcon(QIcon(icon_path+'retext.png')) elif QFile.exists('/usr/share/pixmaps/retext.png'): self.setWindowIcon(QIcon('/usr/share/pixmaps/retext.png')) else: self.setWindowIcon(QIcon.fromTheme('retext', QIcon.fromTheme('accessories-text-editor'))) self.editBoxes = [] self.previewBoxes = [] self.highlighters = [] self.markups = [] self.fileNames = [] self.actionPreviewChecked = [] self.actionLivePreviewChecked = [] self.tabWidget = QTabWidget(self) self.initTabWidget() self.setCentralWidget(self.tabWidget) self.tabWidget.currentChanged.connect(self.changeIndex) self.tabWidget.tabCloseRequested.connect(self.closeTab) toolBar = QToolBar(self.tr('File toolbar'), self) self.addToolBar(Qt.TopToolBarArea, toolBar) self.editBar = QToolBar(self.tr('Edit toolbar'), self) self.addToolBar(Qt.TopToolBarArea, self.editBar) self.searchBar = QToolBar(self.tr('Search toolbar'), self) self.addToolBar(Qt.BottomToolBarArea, self.searchBar) toolBar.setVisible(not globalSettings.hideToolBar) self.editBar.setVisible(not globalSettings.hideToolBar) self.actionNew = self.act(self.tr('New'), 'document-new', self.createNew, shct=QKeySequence.New) self.actionNew.setPriority(QAction.LowPriority) self.actionOpen = self.act(self.tr('Open'), 'document-open', self.openFile, shct=QKeySequence.Open) self.actionOpen.setPriority(QAction.LowPriority) self.actionSetEncoding = self.act(self.tr('Set encoding'), trig=self.showEncodingDialog) self.actionSetEncoding.setEnabled(False) self.actionReload = self.act(self.tr('Reload'), 'view-refresh', trig=self.openFileMain) self.actionReload.setEnabled(False) self.actionSave = self.act(self.tr('Save'), 'document-save', self.saveFile, shct=QKeySequence.Save) self.actionSave.setEnabled(False) self.actionSave.setPriority(QAction.LowPriority) self.actionSaveAs = self.act(self.tr('Save as'), 'document-save-as', self.saveFileAs, shct=QKeySequence.SaveAs) self.actionNextTab = self.act(self.tr('Next tab'), 'go-next', lambda: self.switchTab(1), shct=Qt.CTRL+Qt.Key_PageDown) self.actionPrevTab = self.act(self.tr('Previous tab'), 'go-previous', lambda: self.switchTab(-1), shct=Qt.CTRL+Qt.Key_PageUp) self.actionPrint = self.act(self.tr('Print'), 'document-print', self.printFile, shct=QKeySequence.Print) self.actionPrint.setPriority(QAction.LowPriority) self.actionPrintPreview = self.act(self.tr('Print preview'), 'document-print-preview', self.printPreview) self.actionViewHtml = self.act(self.tr('View HTML code'), 'text-html', self.viewHtml) self.actionChangeFont = self.act(self.tr('Change default font'), trig=self.changeFont) self.actionSearch = self.act(self.tr('Find text'), 'edit-find', shct=QKeySequence.Find) self.actionSearch.setCheckable(True) self.actionSearch.triggered[bool].connect(self.searchBar.setVisible) self.searchBar.visibilityChanged.connect(self.searchBarVisibilityChanged) self.actionPreview = self.act(self.tr('Preview'), shct=Qt.CTRL+Qt.Key_E, trigbool=self.preview) if QIcon.hasThemeIcon('document-preview'): self.actionPreview.setIcon(QIcon.fromTheme('document-preview')) elif QIcon.hasThemeIcon('preview-file'): self.actionPreview.setIcon(QIcon.fromTheme('preview-file')) elif QIcon.hasThemeIcon('x-office-document'): self.actionPreview.setIcon(QIcon.fromTheme('x-office-document')) else: self.actionPreview.setIcon(QIcon(icon_path+'document-preview.png')) self.actionLivePreview = self.act(self.tr('Live preview'), shct=Qt.CTRL+Qt.Key_L, trigbool=self.enableLivePreview) self.actionTableMode = self.act(self.tr('Table mode'), shct=Qt.CTRL+Qt.Key_T, trigbool=lambda x: self.editBoxes[self.ind].enableTableMode(x)) if ReTextFakeVimHandler: self.actionFakeVimMode = self.act(self.tr('FakeVim mode'), shct=Qt.CTRL+Qt.ALT+Qt.Key_V, trigbool=self.enableFakeVimMode) if globalSettings.useFakeVim: self.actionFakeVimMode.setChecked(True) self.enableFakeVimMode(True) self.actionFullScreen = self.act(self.tr('Fullscreen mode'), 'view-fullscreen', shct=Qt.Key_F11, trigbool=self.enableFullScreen) self.actionFullScreen.setPriority(QAction.LowPriority) self.actionConfig = self.act(self.tr('Preferences'), icon='preferences-system', trig=self.openConfigDialog) self.actionConfig.setMenuRole(QAction.PreferencesRole) self.actionSaveHtml = self.act('HTML', 'text-html', self.saveFileHtml) self.actionPdf = self.act('PDF', 'application-pdf', self.savePdf) self.actionOdf = self.act('ODT', 'x-office-document', self.saveOdf) self.getExportExtensionsList() self.actionQuit = self.act(self.tr('Quit'), 'application-exit', shct=QKeySequence.Quit) self.actionQuit.setMenuRole(QAction.QuitRole) self.actionQuit.triggered.connect(self.close) self.actionUndo = self.act(self.tr('Undo'), 'edit-undo', lambda: self.editBoxes[self.ind].undo(), shct=QKeySequence.Undo) self.actionRedo = self.act(self.tr('Redo'), 'edit-redo', lambda: self.editBoxes[self.ind].redo(), shct=QKeySequence.Redo) self.actionCopy = self.act(self.tr('Copy'), 'edit-copy', lambda: self.editBoxes[self.ind].copy(), shct=QKeySequence.Copy) self.actionCut = self.act(self.tr('Cut'), 'edit-cut', lambda: self.editBoxes[self.ind].cut(), shct=QKeySequence.Cut) self.actionPaste = self.act(self.tr('Paste'), 'edit-paste', lambda: self.editBoxes[self.ind].paste(), shct=QKeySequence.Paste) self.actionUndo.setEnabled(False) self.actionRedo.setEnabled(False) self.actionCopy.setEnabled(False) self.actionCut.setEnabled(False) qApp = QApplication.instance() qApp.clipboard().dataChanged.connect(self.clipboardDataChanged) self.clipboardDataChanged() if enchant_available: self.actionEnableSC = self.act(self.tr('Enable'), trigbool=self.enableSpellCheck) self.actionSetLocale = self.act(self.tr('Set locale'), trig=self.changeLocale) self.actionWebKit = self.act(self.tr('Use WebKit renderer'), trigbool=self.enableWebKit) self.actionWebKit.setChecked(globalSettings.useWebKit) self.actionShow = self.act(self.tr('Show directory'), 'system-file-manager', self.showInDir) self.actionFind = self.act(self.tr('Next'), 'go-next', self.find, shct=QKeySequence.FindNext) self.actionFindPrev = self.act(self.tr('Previous'), 'go-previous', lambda: self.find(back=True), shct=QKeySequence.FindPrevious) self.actionHelp = self.act(self.tr('Get help online'), 'help-contents', self.openHelp) self.aboutWindowTitle = self.tr('About %s', 'Example of final string: About ReText') self.aboutWindowTitle = self.aboutWindowTitle % app_name self.actionAbout = self.act(self.aboutWindowTitle, 'help-about', self.aboutDialog) self.actionAbout.setMenuRole(QAction.AboutRole) self.actionAboutQt = self.act(self.tr('About Qt')) self.actionAboutQt.setMenuRole(QAction.AboutQtRole) self.actionAboutQt.triggered.connect(qApp.aboutQt) availableMarkups = markups.get_available_markups() if not availableMarkups: print('Warning: no markups are available!') self.defaultMarkup = availableMarkups[0] if availableMarkups else None if globalSettings.defaultMarkup: mc = markups.find_markup_class_by_name(globalSettings.defaultMarkup) if mc and mc.available(): self.defaultMarkup = mc if len(availableMarkups) > 1: self.chooseGroup = QActionGroup(self) markupActions = [] for markup in availableMarkups: markupAction = self.act(markup.name, trigbool=self.markupFunction(markup)) if markup == self.defaultMarkup: markupAction.setChecked(True) self.chooseGroup.addAction(markupAction) markupActions.append(markupAction) self.actionBold = self.act(self.tr('Bold'), shct=QKeySequence.Bold, trig=lambda: self.insertChars('**')) self.actionItalic = self.act(self.tr('Italic'), shct=QKeySequence.Italic, trig=lambda: self.insertChars('*')) self.actionUnderline = self.act(self.tr('Underline'), shct=QKeySequence.Underline, trig=lambda: self.insertTag('u')) self.usefulTags = ('a', 'big', 'center', 'img', 's', 'small', 'span', 'table', 'td', 'tr', 'u') self.usefulChars = ('deg', 'divide', 'dollar', 'hellip', 'laquo', 'larr', 'lsquo', 'mdash', 'middot', 'minus', 'nbsp', 'ndash', 'raquo', 'rarr', 'rsquo', 'times') self.tagsBox = QComboBox(self.editBar) self.tagsBox.addItem(self.tr('Tags')) self.tagsBox.addItems(self.usefulTags) self.tagsBox.activated.connect(self.insertTag) self.symbolBox = QComboBox(self.editBar) self.symbolBox.addItem(self.tr('Symbols')) self.symbolBox.addItems(self.usefulChars) self.symbolBox.activated.connect(self.insertSymbol) self.updateStyleSheet() menubar = QMenuBar(self) menubar.setGeometry(QRect(0, 0, 800, 25)) self.setMenuBar(menubar) menuFile = menubar.addMenu(self.tr('File')) menuEdit = menubar.addMenu(self.tr('Edit')) menuHelp = menubar.addMenu(self.tr('Help')) menuFile.addAction(self.actionNew) menuFile.addAction(self.actionOpen) self.menuRecentFiles = menuFile.addMenu(self.tr('Open recent')) self.menuRecentFiles.aboutToShow.connect(self.updateRecentFiles) menuFile.addMenu(self.menuRecentFiles) menuFile.addAction(self.actionShow) menuFile.addAction(self.actionSetEncoding) menuFile.addAction(self.actionReload) menuFile.addSeparator() menuFile.addAction(self.actionSave) menuFile.addAction(self.actionSaveAs) menuFile.addSeparator() menuFile.addAction(self.actionNextTab) menuFile.addAction(self.actionPrevTab) menuFile.addSeparator() menuExport = menuFile.addMenu(self.tr('Export')) menuExport.addAction(self.actionSaveHtml) menuExport.addAction(self.actionOdf) menuExport.addAction(self.actionPdf) if self.extensionActions: menuExport.addSeparator() for action, mimetype in self.extensionActions: menuExport.addAction(action) menuExport.aboutToShow.connect(self.updateExtensionsVisibility) menuFile.addAction(self.actionPrint) menuFile.addAction(self.actionPrintPreview) menuFile.addSeparator() menuFile.addAction(self.actionQuit) menuEdit.addAction(self.actionUndo) menuEdit.addAction(self.actionRedo) menuEdit.addSeparator() menuEdit.addAction(self.actionCut) menuEdit.addAction(self.actionCopy) menuEdit.addAction(self.actionPaste) menuEdit.addSeparator() if enchant_available: menuSC = menuEdit.addMenu(self.tr('Spell check')) menuSC.addAction(self.actionEnableSC) menuSC.addAction(self.actionSetLocale) menuEdit.addAction(self.actionSearch) menuEdit.addAction(self.actionChangeFont) menuEdit.addSeparator() if len(availableMarkups) > 1: self.menuMode = menuEdit.addMenu(self.tr('Default markup')) for markupAction in markupActions: self.menuMode.addAction(markupAction) menuFormat = menuEdit.addMenu(self.tr('Formatting')) menuFormat.addAction(self.actionBold) menuFormat.addAction(self.actionItalic) menuFormat.addAction(self.actionUnderline) menuEdit.addAction(self.actionWebKit) menuEdit.addSeparator() menuEdit.addAction(self.actionViewHtml) menuEdit.addAction(self.actionLivePreview) menuEdit.addAction(self.actionPreview) menuEdit.addAction(self.actionTableMode) if ReTextFakeVimHandler: menuEdit.addAction(self.actionFakeVimMode) menuEdit.addSeparator() menuEdit.addAction(self.actionFullScreen) menuEdit.addAction(self.actionConfig) menuHelp.addAction(self.actionHelp) menuHelp.addSeparator() menuHelp.addAction(self.actionAbout) menuHelp.addAction(self.actionAboutQt) menubar.addMenu(menuFile) menubar.addMenu(menuEdit) menubar.addMenu(menuHelp) toolBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) toolBar.addAction(self.actionNew) toolBar.addSeparator() toolBar.addAction(self.actionOpen) toolBar.addAction(self.actionSave) toolBar.addAction(self.actionPrint) toolBar.addSeparator() toolBar.addAction(self.actionPreview) toolBar.addAction(self.actionFullScreen) self.editBar.addAction(self.actionUndo) self.editBar.addAction(self.actionRedo) self.editBar.addSeparator() self.editBar.addAction(self.actionCut) self.editBar.addAction(self.actionCopy) self.editBar.addAction(self.actionPaste) self.editBar.addSeparator() self.editBar.addWidget(self.tagsBox) self.editBar.addWidget(self.symbolBox) self.searchEdit = QLineEdit(self.searchBar) self.searchEdit.setPlaceholderText(self.tr('Search')) self.searchEdit.returnPressed.connect(self.find) self.csBox = QCheckBox(self.tr('Case sensitively'), self.searchBar) self.searchBar.addWidget(self.searchEdit) self.searchBar.addSeparator() self.searchBar.addWidget(self.csBox) self.searchBar.addAction(self.actionFindPrev) self.searchBar.addAction(self.actionFind) self.searchBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) self.searchBar.setVisible(False) self.autoSaveEnabled = globalSettings.autoSave if self.autoSaveEnabled: timer = QTimer(self) timer.start(60000) timer.timeout.connect(self.saveAll) self.ind = None if enchant_available: self.sl = globalSettings.spellCheckLocale if self.sl: try: enchant.Dict(self.sl) except Exception as e: print(e, file=sys.stderr) self.sl = None if globalSettings.spellCheck: self.actionEnableSC.setChecked(True) self.enableSpellCheck(True) self.fileSystemWatcher = QFileSystemWatcher() self.fileSystemWatcher.fileChanged.connect(self.fileChanged) def initConfig(self): self.font = None if globalSettings.font: self.font = QFont(globalSettings.font) if self.font and globalSettings.fontSize: self.font.setPointSize(globalSettings.fontSize) def updateStyleSheet(self): if globalSettings.styleSheet: sheetfile = QFile(globalSettings.styleSheet) sheetfile.open(QIODevice.ReadOnly) self.ss = QTextStream(sheetfile).readAll() sheetfile.close() else: self.ss = '' def initTabWidget(self): def dragEnterEvent(e): e.acceptProposedAction() def dropEvent(e): fn = bytes(e.mimeData().data('text/plain')).decode().rstrip() if fn.startswith('file:'): fn = QUrl(fn).toLocalFile() self.openFileWrapper(fn) self.tabWidget.setTabsClosable(True) self.tabWidget.setAcceptDrops(True) self.tabWidget.dragEnterEvent = dragEnterEvent self.tabWidget.dropEvent = dropEvent def act(self, name, icon=None, trig=None, trigbool=None, shct=None): if not isinstance(shct, QKeySequence): shct = QKeySequence(shct) if icon: action = QAction(self.actIcon(icon), name, self) else: action = QAction(name, self) if trig: action.triggered.connect(trig) elif trigbool: action.setCheckable(True) action.triggered[bool].connect(trigbool) if shct: action.setShortcut(shct) return action def actIcon(self, name): return QIcon.fromTheme(name, QIcon(icon_path+name+'.png')) def printError(self): import traceback print('Exception occured while parsing document:', file=sys.stderr) traceback.print_exc() def getSplitter(self, index): splitter = QSplitter(Qt.Horizontal) # Give both boxes a minimum size so the minimumSizeHint will be # ignored when splitter.setSizes is called below for widget in self.editBoxes[index], self.previewBoxes[index]: widget.setMinimumWidth(125) splitter.addWidget(widget) splitter.setSizes((50, 50)) splitter.setChildrenCollapsible(False) return splitter def getWebView(self): webView = QWebView() if not globalSettings.handleWebLinks: webView.page().setLinkDelegationPolicy(QWebPage.DelegateExternalLinks) webView.page().linkClicked.connect(QDesktopServices.openUrl) webView.settings().setAttribute(QWebSettings.LocalContentCanAccessFileUrls, False) return webView def createTab(self, fileName): self.previewBlocked = False self.editBoxes.append(ReTextEdit(self)) self.highlighters.append(ReTextHighlighter(self.editBoxes[-1].document())) if enchant_available and self.actionEnableSC.isChecked(): self.highlighters[-1].dictionary = \ enchant.Dict(self.sl) if self.sl else enchant.Dict() self.highlighters[-1].rehighlight() if globalSettings.useWebKit: self.previewBoxes.append(self.getWebView()) else: self.previewBoxes.append(QTextBrowser()) self.previewBoxes[-1].setOpenExternalLinks(True) self.previewBoxes[-1].setVisible(False) self.fileNames.append(fileName) markupClass = self.getMarkupClass(fileName) self.markups.append(self.getMarkup(fileName)) self.highlighters[-1].docType = (markupClass.name if markupClass else '') liveMode = globalSettings.restorePreviewState and globalSettings.previewState self.actionPreviewChecked.append(liveMode) self.actionLivePreviewChecked.append(liveMode) metrics = QFontMetrics(self.editBoxes[-1].font()) self.editBoxes[-1].setTabStopWidth(globalSettings.tabWidth * metrics.width(' ')) self.editBoxes[-1].textChanged.connect(self.updateLivePreviewBox) self.editBoxes[-1].undoAvailable.connect(self.actionUndo.setEnabled) self.editBoxes[-1].redoAvailable.connect(self.actionRedo.setEnabled) self.editBoxes[-1].copyAvailable.connect(self.enableCopy) self.editBoxes[-1].document().modificationChanged.connect(self.modificationChanged) if globalSettings.useFakeVim: self.installFakeVimHandler(self.editBoxes[-1]) return self.getSplitter(-1) def closeTab(self, ind): if self.maybeSave(ind): if self.tabWidget.count() == 1: self.tabWidget.addTab(self.createTab(""), self.tr("New document")) if self.fileNames[ind]: self.fileSystemWatcher.removePath(self.fileNames[ind]) del self.editBoxes[ind] del self.previewBoxes[ind] del self.highlighters[ind] del self.markups[ind] del self.fileNames[ind] del self.actionPreviewChecked[ind] del self.actionLivePreviewChecked[ind] self.tabWidget.removeTab(ind) def getMarkupClass(self, fileName=None): if fileName is None: fileName = self.fileNames[self.ind] if fileName: markupClass = markups.get_markup_for_file_name( fileName, return_class=True) if markupClass: return markupClass return self.defaultMarkup def getMarkup(self, fileName=None): if fileName is None: fileName = self.fileNames[self.ind] markupClass = self.getMarkupClass(fileName=fileName) if markupClass and markupClass.available(): return markupClass(filename=fileName) def docTypeChanged(self): oldType = self.highlighters[self.ind].docType markupClass = self.getMarkupClass() newType = markupClass.name if markupClass else '' if oldType != newType: self.markups[self.ind] = self.getMarkup() self.updatePreviewBox() self.highlighters[self.ind].docType = newType self.highlighters[self.ind].rehighlight() dtMarkdown = (newType == DOCTYPE_MARKDOWN) dtMkdOrReST = (newType in (DOCTYPE_MARKDOWN, DOCTYPE_REST)) self.tagsBox.setEnabled(dtMarkdown) self.symbolBox.setEnabled(dtMarkdown) self.actionUnderline.setEnabled(dtMarkdown) self.actionBold.setEnabled(dtMkdOrReST) self.actionItalic.setEnabled(dtMkdOrReST) canReload = bool(self.fileNames[self.ind]) and not self.autoSaveActive() self.actionSetEncoding.setEnabled(canReload) self.actionReload.setEnabled(canReload) def changeIndex(self, ind): if ind > -1: self.actionUndo.setEnabled(self.editBoxes[ind].document().isUndoAvailable()) self.actionRedo.setEnabled(self.editBoxes[ind].document().isRedoAvailable()) self.actionCopy.setEnabled(self.editBoxes[ind].textCursor().hasSelection()) self.actionCut.setEnabled(self.editBoxes[ind].textCursor().hasSelection()) self.actionPreview.setChecked(self.actionPreviewChecked[ind]) self.actionLivePreview.setChecked(self.actionLivePreviewChecked[ind]) self.actionTableMode.setChecked(self.editBoxes[ind].tableModeEnabled) self.editBar.setDisabled(self.actionPreviewChecked[ind]) self.ind = ind if self.fileNames[ind]: self.setCurrentFile() else: self.setWindowTitle(self.tr('New document') + '[*]') self.docTypeChanged() self.modificationChanged(self.editBoxes[ind].document().isModified()) if globalSettings.restorePreviewState: globalSettings.previewState = self.actionLivePreviewChecked[ind] if self.actionLivePreviewChecked[ind]: self.enableLivePreview(True) self.editBoxes[self.ind].setFocus(Qt.OtherFocusReason) def changeFont(self): if not self.font: self.font = QFont() fd = QFontDialog.getFont(self.font, self) if fd[1]: self.font = QFont() self.font.setFamily(fd[0].family()) settings.setValue('font', fd[0].family()) self.font.setPointSize(fd[0].pointSize()) settings.setValue('fontSize', fd[0].pointSize()) self.updatePreviewBox() def preview(self, viewmode): self.actionPreviewChecked[self.ind] = viewmode if self.actionLivePreview.isChecked(): self.actionLivePreview.setChecked(False) return self.enableLivePreview(False) self.editBar.setDisabled(viewmode) self.editBoxes[self.ind].setVisible(not viewmode) self.previewBoxes[self.ind].setVisible(viewmode) if viewmode: self.updatePreviewBox() def enableLivePreview(self, livemode): if globalSettings.restorePreviewState: globalSettings.previewState = livemode self.actionLivePreviewChecked[self.ind] = livemode self.actionPreviewChecked[self.ind] = livemode self.actionPreview.setChecked(livemode) self.editBar.setEnabled(True) self.previewBoxes[self.ind].setVisible(livemode) self.editBoxes[self.ind].setVisible(True) if livemode: self.updatePreviewBox() def enableWebKit(self, enable): globalSettings.useWebKit = enable oldind = self.ind self.tabWidget.clear() for self.ind in range(len(self.editBoxes)): if enable: self.previewBoxes[self.ind] = self.getWebView() else: self.previewBoxes[self.ind] = QTextBrowser() self.previewBoxes[self.ind].setOpenExternalLinks(True) splitter = self.getSplitter(self.ind) self.tabWidget.addTab(splitter, self.getDocumentTitle(baseName=True)) self.updatePreviewBox() self.previewBoxes[self.ind].setVisible(self.actionPreviewChecked[self.ind]) self.ind = oldind self.tabWidget.setCurrentIndex(self.ind) def enableCopy(self, copymode): self.actionCopy.setEnabled(copymode) self.actionCut.setEnabled(copymode) def enableFullScreen(self, yes): if yes: self.showFullScreen() else: self.showNormal() def openConfigDialog(self): dlg = ConfigDialog(self) dlg.setWindowTitle(self.tr('Preferences')) dlg.show() def installFakeVimHandler(self, editor): if ReTextFakeVimHandler: fakeVimEditor = ReTextFakeVimHandler(editor, self) fakeVimEditor.setSaveAction(self.actionSave) fakeVimEditor.setQuitAction(self.actionQuit) self.actionFakeVimMode.triggered.connect(fakeVimEditor.remove) def enableFakeVimMode(self, yes): globalSettings.useFakeVim = yes if yes: FakeVimMode.init(self) for editor in self.editBoxes: self.installFakeVimHandler(editor) else: FakeVimMode.exit(self) def enableSpellCheck(self, yes): if yes: if self.sl: self.setAllDictionaries(enchant.Dict(self.sl)) else: self.setAllDictionaries(enchant.Dict()) else: self.setAllDictionaries(None) globalSettings.spellCheck = yes def setAllDictionaries(self, dictionary): for hl in self.highlighters: hl.dictionary = dictionary hl.rehighlight() def changeLocale(self): if self.sl: localedlg = LocaleDialog(self, defaultText=self.sl) else: localedlg = LocaleDialog(self) if localedlg.exec() != QDialog.Accepted: return sl = localedlg.localeEdit.text() setdefault = localedlg.checkBox.isChecked() if sl: try: sl = str(sl) enchant.Dict(sl) except Exception as e: QMessageBox.warning(self, '', str(e)) else: self.sl = sl self.enableSpellCheck(self.actionEnableSC.isChecked()) else: self.sl = None self.enableSpellCheck(self.actionEnableSC.isChecked()) if setdefault: globalSettings.spellCheckLocale = sl def searchBarVisibilityChanged(self, visible): self.actionSearch.setChecked(visible) if visible: self.searchEdit.setFocus(Qt.ShortcutFocusReason) def find(self, back=False): flags = QTextDocument.FindFlags() if back: flags |= QTextDocument.FindBackward if self.csBox.isChecked(): flags |= QTextDocument.FindCaseSensitively text = self.searchEdit.text() editBox = self.editBoxes[self.ind] cursor = editBox.textCursor() newCursor = editBox.document().find(text, cursor, flags) if not newCursor.isNull(): editBox.setTextCursor(newCursor) return self.setSearchEditColor(True) cursor.movePosition(QTextCursor.End if back else QTextCursor.Start) newCursor = editBox.document().find(text, cursor, flags) if not newCursor.isNull(): editBox.setTextCursor(newCursor) return self.setSearchEditColor(True) self.setSearchEditColor(False) def setSearchEditColor(self, found): palette = self.searchEdit.palette() palette.setColor(QPalette.Active, QPalette.Base, Qt.white if found else QColor(255, 102, 102)) self.searchEdit.setPalette(palette) def getHtml(self, includeStyleSheet=True, includeTitle=True, includeMeta=False, styleForWebKit=False, webenv=False): if self.markups[self.ind] is None: markupClass = self.getMarkupClass() errMsg = self.tr('Could not parse file contents, check if ' 'you have the <a href="%s">necessary module</a> installed!') try: errMsg %= markupClass.attributes[MODULE_HOME_PAGE] except (AttributeError, KeyError): # Remove the link if markupClass doesn't have the needed attribute errMsg = errMsg.replace('<a href="%s">', '') errMsg = errMsg.replace('</a>', '') return '<p style="color: red">%s</p>' % errMsg text = self.editBoxes[self.ind].toPlainText() headers = '' if includeStyleSheet: fontline = '' if styleForWebKit: fontname = self.font.family() if self.font else 'Sans' fontsize = (self.font if self.font else QFont()).pointSize() fontline = 'body { font-family: %s; font-size: %spt }\n' % \ (fontname, fontsize) headers += '<style type="text/css">\n' + fontline + self.ss + '</style>\n' cssFileName = self.getDocumentTitle(baseName=True)+'.css' if QFile(cssFileName).exists(): headers += '<link rel="stylesheet" type="text/css" href="%s">\n' \ % cssFileName if includeMeta: headers += '<meta name="generator" content="%s %s">\n' % \ (app_name, app_version) fallbackTitle = self.getDocumentTitle() if includeTitle else '' return self.markups[self.ind].get_whole_html(text, custom_headers=headers, include_stylesheet=includeStyleSheet, fallback_title=fallbackTitle, webenv=webenv) def updatePreviewBox(self): self.previewBlocked = False pb = self.previewBoxes[self.ind] textedit = isinstance(pb, QTextEdit) if textedit: scrollbar = pb.verticalScrollBar() disttobottom = scrollbar.maximum() - scrollbar.value() else: frame = pb.page().mainFrame() scrollpos = frame.scrollPosition() try: html = self.getHtml(styleForWebKit=(not textedit)) except Exception: return self.printError() if textedit: pb.setHtml(html) else: pb.setHtml(html, QUrl.fromLocalFile(self.fileNames[self.ind])) if self.font and textedit: pb.document().setDefaultFont(self.font) if textedit: scrollbar.setValue(scrollbar.maximum() - disttobottom) else: frame.setScrollPosition(scrollpos) def updateLivePreviewBox(self): if self.actionLivePreview.isChecked() and self.previewBlocked == False: self.previewBlocked = True QTimer.singleShot(1000, self.updatePreviewBox) def showInDir(self): if self.fileNames[self.ind]: path = QFileInfo(self.fileNames[self.ind]).path() QDesktopServices.openUrl(QUrl.fromLocalFile(path)) else: QMessageBox.warning(self, '', self.tr("Please, save the file somewhere.")) def setCurrentFile(self): self.setWindowTitle("") self.tabWidget.setTabText(self.ind, self.getDocumentTitle(baseName=True)) self.setWindowFilePath(self.fileNames[self.ind]) files = readListFromSettings("recentFileList") while self.fileNames[self.ind] in files: files.remove(self.fileNames[self.ind]) files.insert(0, self.fileNames[self.ind]) if len(files) > 10: del files[10:] writeListToSettings("recentFileList", files) QDir.setCurrent(QFileInfo(self.fileNames[self.ind]).dir().path()) self.docTypeChanged() def createNew(self, text=None): self.tabWidget.addTab(self.createTab(""), self.tr("New document")) self.ind = self.tabWidget.count()-1 self.tabWidget.setCurrentIndex(self.ind) if text: self.editBoxes[self.ind].textCursor().insertText(text) def switchTab(self, shift=1): self.tabWidget.setCurrentIndex((self.ind + shift) % self.tabWidget.count()) def updateRecentFiles(self): self.menuRecentFiles.clear() self.recentFilesActions = [] filesOld = readListFromSettings("recentFileList") files = [] for f in filesOld: if QFile.exists(f): files.append(f) self.recentFilesActions.append(self.act(f, trig=self.openFunction(f))) writeListToSettings("recentFileList", files) for action in self.recentFilesActions: self.menuRecentFiles.addAction(action) def markupFunction(self, markup): return lambda: self.setDefaultMarkup(markup) def openFunction(self, fileName): return lambda: self.openFileWrapper(fileName) def extensionFuntion(self, data): return lambda: \ self.runExtensionCommand(data['Exec'], data['FileFilter'], data['DefaultExtension']) def getExportExtensionsList(self): extensions = [] for extsprefix in datadirs: extsdir = QDir(extsprefix+'/export-extensions/') if extsdir.exists(): for fileInfo in extsdir.entryInfoList(['*.desktop', '*.ini'], QDir.Files | QDir.Readable): extensions.append(self.readExtension(fileInfo.filePath())) locale = QLocale.system().name() self.extensionActions = [] for extension in extensions: try: if ('Name[%s]' % locale) in extension: name = extension['Name[%s]' % locale] elif ('Name[%s]' % locale.split('_')[0]) in extension: name = extension['Name[%s]' % locale.split('_')[0]] else: name = extension['Name'] data = {} for prop in ('FileFilter', 'DefaultExtension', 'Exec'): if 'X-ReText-'+prop in extension: data[prop] = extension['X-ReText-'+prop] elif prop in extension: data[prop] = extension[prop] else: data[prop] = '' action = self.act(name, trig=self.extensionFuntion(data)) if 'Icon' in extension: action.setIcon(self.actIcon(extension['Icon'])) mimetype = extension['MimeType'] if 'MimeType' in extension else None except KeyError: print('Failed to parse extension: Name is required', file=sys.stderr) else: self.extensionActions.append((action, mimetype)) def updateExtensionsVisibility(self): markupClass = self.getMarkupClass() for action in self.extensionActions: if markupClass is None: action[0].setEnabled(False) continue mimetype = action[1] if mimetype == None: enabled = True elif markupClass == markups.MarkdownMarkup: enabled = (mimetype in ("text/x-retext-markdown", "text/x-markdown")) elif markupClass == markups.ReStructuredTextMarkup: enabled = (mimetype in ("text/x-retext-rst", "text/x-rst")) else: enabled = False action[0].setEnabled(enabled) def readExtension(self, fileName): extFile = QFile(fileName) extFile.open(QIODevice.ReadOnly) extension = {} stream = QTextStream(extFile) while not stream.atEnd(): line = stream.readLine() if '=' in line: index = line.index('=') extension[line[:index].rstrip()] = line[index+1:].lstrip() extFile.close() return extension def openFile(self): supportedExtensions = ['.txt'] for markup in markups.get_all_markups(): supportedExtensions += markup.file_extensions fileFilter = ' (' + str.join(' ', ['*'+ext for ext in supportedExtensions]) + ');;' fileNames = QFileDialog.getOpenFileNames(self, self.tr("Select one or several files to open"), "", self.tr("Supported files") + fileFilter + self.tr("All files (*)")) for fileName in fileNames[0]: self.openFileWrapper(fileName) def openFileWrapper(self, fileName): if not fileName: return fileName = QFileInfo(fileName).canonicalFilePath() exists = False for i in range(self.tabWidget.count()): if self.fileNames[i] == fileName: exists = True ex = i if exists: self.tabWidget.setCurrentIndex(ex) elif QFile.exists(fileName): noEmptyTab = ( (self.ind is None) or self.fileNames[self.ind] or self.editBoxes[self.ind].toPlainText() or self.editBoxes[self.ind].document().isModified() ) if noEmptyTab: self.tabWidget.addTab(self.createTab(fileName), "") self.ind = self.tabWidget.count()-1 self.tabWidget.setCurrentIndex(self.ind) if fileName: self.fileSystemWatcher.addPath(fileName) self.fileNames[self.ind] = fileName self.openFileMain() def openFileMain(self, encoding=None): openfile = QFile(self.fileNames[self.ind]) openfile.open(QIODevice.ReadOnly) stream = QTextStream(openfile) if encoding: stream.setCodec(encoding) elif globalSettings.defaultCodec: stream.setCodec(globalSettings.defaultCodec) text = stream.readAll() openfile.close() markupClass = markups.get_markup_for_file_name( self.fileNames[self.ind], return_class=True) self.highlighters[self.ind].docType = (markupClass.name if markupClass else '') self.markups[self.ind] = self.getMarkup() if self.defaultMarkup: self.highlighters[self.ind].docType = self.defaultMarkup.name editBox = self.editBoxes[self.ind] modified = bool(encoding) and (editBox.toPlainText() != text) editBox.setPlainText(text) self.setCurrentFile() editBox.document().setModified(modified) self.setWindowModified(modified) def showEncodingDialog(self): if not self.maybeSave(self.ind): return encoding, ok = QInputDialog.getItem(self, '', self.tr('Select file encoding from the list:'), [bytes(b).decode() for b in QTextCodec.availableCodecs()], 0, False) if ok: self.openFileMain(encoding) def saveFile(self): self.saveFileMain(dlg=False) def saveFileAs(self): self.saveFileMain(dlg=True) def saveAll(self): oldind = self.ind for self.ind in range(self.tabWidget.count()): if self.fileNames[self.ind] and QFileInfo(self.fileNames[self.ind]).isWritable(): self.saveFileCore(self.fileNames[self.ind]) self.editBoxes[self.ind].document().setModified(False) self.ind = oldind def saveFileMain(self, dlg): if (not self.fileNames[self.ind]) or dlg: markupClass = self.getMarkupClass() if (markupClass is None) or not hasattr(markupClass, 'default_extension'): defaultExt = self.tr("Plain text (*.txt)") ext = ".txt" else: defaultExt = self.tr('%s files', 'Example of final string: Markdown files') \ % markupClass.name + ' (' + str.join(' ', ('*'+extension for extension in markupClass.file_extensions)) + ')' if markupClass == markups.MarkdownMarkup: ext = globalSettings.markdownDefaultFileExtension elif markupClass == markups.ReStructuredTextMarkup: ext = globalSettings.restDefaultFileExtension else: ext = markupClass.default_extension newFileName = QFileDialog.getSaveFileName(self, self.tr("Save file"), "", defaultExt)[0] if newFileName: if not QFileInfo(newFileName).suffix(): newFileName += ext if self.fileNames[self.ind]: self.fileSystemWatcher.removePath(self.fileNames[self.ind]) self.fileNames[self.ind] = newFileName self.actionSetEncoding.setDisabled(self.autoSaveActive()) if self.fileNames[self.ind]: result = self.saveFileCore(self.fileNames[self.ind]) if result: self.setCurrentFile() self.editBoxes[self.ind].document().setModified(False) self.setWindowModified(False) return True else: QMessageBox.warning(self, '', self.tr("Cannot save to file because it is read-only!")) return False def saveFileCore(self, fn): self.fileSystemWatcher.removePath(fn) savefile = QFile(fn) result = savefile.open(QIODevice.WriteOnly) if result: savestream = QTextStream(savefile) if globalSettings.defaultCodec: savestream.setCodec(globalSettings.defaultCodec) savestream << self.editBoxes[self.ind].toPlainText() savefile.close() self.fileSystemWatcher.addPath(fn) return result def saveHtml(self, fileName): if not QFileInfo(fileName).suffix(): fileName += ".html" try: htmltext = self.getHtml(includeStyleSheet=False, includeMeta=True, webenv=True) except Exception: return self.printError() htmlFile = QFile(fileName) htmlFile.open(QIODevice.WriteOnly) html = QTextStream(htmlFile) if globalSettings.defaultCodec: html.setCodec(globalSettings.defaultCodec) html << htmltext htmlFile.close() def textDocument(self): td = QTextDocument() td.setMetaInformation(QTextDocument.DocumentTitle, self.getDocumentTitle()) if self.ss: td.setDefaultStyleSheet(self.ss) td.setHtml(self.getHtml()) if self.font: td.setDefaultFont(self.font) return td def saveOdf(self): try: document = self.textDocument() except Exception: return self.printError() fileName = QFileDialog.getSaveFileName(self, self.tr("Export document to ODT"), "", self.tr("OpenDocument text files (*.odt)"))[0] if not QFileInfo(fileName).suffix(): fileName += ".odt" writer = QTextDocumentWriter(fileName) writer.setFormat("odf") writer.write(document) def saveFileHtml(self): fileName = QFileDialog.getSaveFileName(self, self.tr("Save file"), "", self.tr("HTML files (*.html *.htm)"))[0] if fileName: self.saveHtml(fileName) def getDocumentForPrint(self): if globalSettings.useWebKit: return self.previewBoxes[self.ind] try: return self.textDocument() except Exception: self.printError() def standardPrinter(self): printer = QPrinter(QPrinter.HighResolution) printer.setDocName(self.getDocumentTitle()) printer.setCreator(app_name+" "+app_version) return printer def savePdf(self): self.updatePreviewBox() fileName = QFileDialog.getSaveFileName(self, self.tr("Export document to PDF"), "", self.tr("PDF files (*.pdf)"))[0] if fileName: if not QFileInfo(fileName).suffix(): fileName += ".pdf" printer = self.standardPrinter() printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(fileName) document = self.getDocumentForPrint() if document != None: document.print(printer) def printFile(self): self.updatePreviewBox() printer = self.standardPrinter() dlg = QPrintDialog(printer, self) dlg.setWindowTitle(self.tr("Print document")) if (dlg.exec() == QDialog.Accepted): document = self.getDocumentForPrint() if document != None: document.print(printer) def printPreview(self): document = self.getDocumentForPrint() if document == None: return printer = self.standardPrinter() preview = QPrintPreviewDialog(printer, self) preview.paintRequested.connect(document.print) preview.exec() def runExtensionCommand(self, command, filefilter, defaultext): of = ('%of' in command) html = ('%html' in command) if of: if defaultext and not filefilter: filefilter = '*'+defaultext fileName = QFileDialog.getSaveFileName(self, self.tr('Export document'), '', filefilter)[0] if not fileName: return if defaultext and not QFileInfo(fileName).suffix(): fileName += defaultext basename = '.%s.retext-temp' % self.getDocumentTitle(baseName=True) if html: tmpname = basename+'.html' self.saveHtml(tmpname) else: tmpname = basename+self.getMarkupClass().default_extension self.saveFileCore(tmpname) command = command.replace('%of', '"out'+defaultext+'"') command = command.replace('%html' if html else '%if', '"'+tmpname+'"') try: Popen(str(command), shell=True).wait() except Exception as error: errorstr = str(error) QMessageBox.warning(self, '', self.tr('Failed to execute the command:') + '\n' + errorstr) QFile(tmpname).remove() if of: QFile('out'+defaultext).rename(fileName) def getDocumentTitle(self, baseName=False): markup = self.markups[self.ind] realTitle = '' if markup and not baseName: text = self.editBoxes[self.ind].toPlainText() try: realTitle = markup.get_document_title(text) except Exception: self.printError() if realTitle: return realTitle elif self.fileNames[self.ind]: fileinfo = QFileInfo(self.fileNames[self.ind]) basename = fileinfo.completeBaseName() return (basename if basename else fileinfo.fileName()) return self.tr("New document") def autoSaveActive(self): return self.autoSaveEnabled and self.fileNames[self.ind] and \ QFileInfo(self.fileNames[self.ind]).isWritable() def modificationChanged(self, changed): if self.autoSaveActive(): changed = False self.actionSave.setEnabled(changed) self.setWindowModified(changed) def clipboardDataChanged(self): mimeData = QApplication.instance().clipboard().mimeData() if mimeData is not None: self.actionPaste.setEnabled(mimeData.hasText()) def insertChars(self, chars): tc = self.editBoxes[self.ind].textCursor() if tc.hasSelection(): selection = tc.selectedText() if selection.startswith(chars) and selection.endswith(chars): if len(selection) > 2*len(chars): selection = selection[len(chars):-len(chars)] tc.insertText(selection) else: tc.insertText(chars+tc.selectedText()+chars) else: tc.insertText(chars) def insertTag(self, ut): if not ut: return if isinstance(ut, int): ut = self.usefulTags[ut - 1] arg = ' style=""' if ut == 'span' else '' tc = self.editBoxes[self.ind].textCursor() if ut == 'img': toinsert = ('<a href="' + tc.selectedText() + '" target="_blank"><img src="' + tc.selectedText() + '"/></a>') elif ut == 'a': toinsert = ('<a href="' + tc.selectedText() + '" target="_blank">' + tc.selectedText() + '</a>') else: toinsert = '<'+ut+arg+'>'+tc.selectedText()+'</'+ut+'>' tc.insertText(toinsert) self.tagsBox.setCurrentIndex(0) def insertSymbol(self, num): if num: self.editBoxes[self.ind].insertPlainText('&'+self.usefulChars[num-1]+';') self.symbolBox.setCurrentIndex(0) def fileChanged(self, fileName): ind = self.fileNames.index(fileName) self.tabWidget.setCurrentIndex(ind) if not QFile.exists(fileName): self.editBoxes[ind].document().setModified(True) QMessageBox.warning(self, '', self.tr( 'This file has been deleted by other application.\n' 'Please make sure you save the file before exit.')) elif not self.editBoxes[ind].document().isModified(): # File was not modified in ReText, reload silently self.openFileMain() self.updatePreviewBox() else: text = self.tr( 'This document has been modified by other application.\n' 'Do you want to reload the file (this will discard all ' 'your changes)?\n') if self.autoSaveEnabled: text += self.tr( 'If you choose to not reload the file, auto save mode will ' 'be disabled for this session to prevent data loss.') messageBox = QMessageBox(QMessageBox.Warning, '', text) reloadButton = messageBox.addButton(self.tr('Reload'), QMessageBox.YesRole) messageBox.addButton(QMessageBox.Cancel) messageBox.exec() if messageBox.clickedButton() is reloadButton: self.openFileMain() self.updatePreviewBox() else: self.autoSaveEnabled = False self.editBoxes[ind].document().setModified(True) if fileName not in self.fileSystemWatcher.files(): # https://sourceforge.net/p/retext/tickets/137/ self.fileSystemWatcher.addPath(fileName) def maybeSave(self, ind): if self.autoSaveActive(): self.saveFileCore(self.fileNames[self.ind]) return True if not self.editBoxes[ind].document().isModified(): return True self.tabWidget.setCurrentIndex(ind) ret = QMessageBox.warning(self, '', self.tr("The document has been modified.\nDo you want to save your changes?"), QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel) if ret == QMessageBox.Save: return self.saveFileMain(False) elif ret == QMessageBox.Cancel: return False return True def closeEvent(self, closeevent): for self.ind in range(self.tabWidget.count()): if not self.maybeSave(self.ind): return closeevent.ignore() if globalSettings.saveWindowGeometry and not self.isMaximized(): globalSettings.windowGeometry = self.saveGeometry() closeevent.accept() def viewHtml(self): htmlDlg = HtmlDialog(self) try: htmltext = self.getHtml(includeStyleSheet=False, includeTitle=False) except Exception: return self.printError() winTitle = self.getDocumentTitle(baseName=True) htmlDlg.setWindowTitle(winTitle+" ("+self.tr("HTML code")+")") htmlDlg.textEdit.setPlainText(htmltext.rstrip()) htmlDlg.hl.rehighlight() htmlDlg.show() htmlDlg.raise_() htmlDlg.activateWindow() def openHelp(self): QDesktopServices.openUrl(QUrl('http://sourceforge.net/p/retext/home/Help and Support')) def aboutDialog(self): QMessageBox.about(self, self.aboutWindowTitle, '<p><b>' + (self.tr('ReText %s (using PyMarkups %s)') % (app_version, markups.__version__)) +'</b></p>' + self.tr('Simple but powerful editor' ' for Markdown and reStructuredText') +'</p><p>'+self.tr('Author: Dmitry Shachnev, 2011').replace('2011', '2011\u2013' '2015') +'<br><a href="http://sourceforge.net/p/retext/">'+self.tr('Website') +'</a> | <a href="http://daringfireball.net/projects/markdown/syntax">' +self.tr('Markdown syntax') +'</a> | <a href="http://docutils.sourceforge.net/docs/user/rst/quickref.html">' +self.tr('reStructuredText syntax')+'</a></p>') def setDefaultMarkup(self, markup): self.defaultMarkup = markup defaultName = markups.get_available_markups()[0].name writeToSettings('defaultMarkup', markup.name, defaultName) oldind = self.ind for self.ind in range(len(self.previewBoxes)): self.docTypeChanged() self.ind = oldind
class Text(DesignItem): def __init__(self, text, scene): super(Text, self).__init__(scene) self.font = QFont("Arial") self.font.setPointSize(14) self.font.setStyleName("Standard") self.text = text self.textcolor = QColor(Qt.black) self.data = str.encode(self.getSvg()) self.renderer = QSvgRenderer() self.renderer.load(self.data) self.svg = QGraphicsSvgItem(self) self.svg.setSharedRenderer(self.renderer) self.setRect(0, 0, self.svg.boundingRect().width(), self.svg.boundingRect().height()) def typeName(self): return "Text" def paint(self, paint, option, widget): if option.state & QStyle.State_Selected: self.drawHighlightSelected(paint, option) def getTextTag(self, id): fm = QFontMetrics(self.font) svg = "<text " if id: svg += "id=\"" + id + "\" " svg += "x=\"0\" y=\"" + str(fm.ascent()) + "\" " svg += "font-family=\"" + self.font.family() + "\" " svg += "font-size=\"" + str(self.font.pointSize() * 1.25) + "px\" " if self.font.bold(): svg += "font-weight=\"bold\" " if self.font.italic(): svg += "font-style=\"italic\" " svg += "fill=\"" + self.textcolor.name() + "\" " svg += "opacity=\"" + str(self.opacity()) + "\" " svg += ">" svg += self.text svg += "</text>" return svg def getSvg(self): font = QFont(self.font.family()) font.setBold(self.font.bold()) font.setItalic(self.font.italic()) font.setPixelSize(self.font.pointSize() * 1.25) fm = QFontMetrics(font) self.width = fm.width(self.text) + 2 self.height = fm.height() svg = "<svg width=\"" + str(self.width) + "\" " svg += "height=\"" + str(self.height) + "\" >" svg += self.getTextTag("") svg += "</svg>" return svg def setScale(self, x, y): self.xscale = x self.yscale = y trans = QTransform() trans.scale(self.xscale, self.yscale) self.svg.setTransform(trans) self.setRect(0, 0, self.svg.boundingRect().width() * x, self.svg.boundingRect().height() * y) def scaleObjects(self): self.xscale = self.rect.width() / self.svg.boundingRect().width() self.yscale = self.rect.height() / self.svg.boundingRect().height() trans = QTransform() trans.scale(self.xscale, self.yscale) self.svg.setTransform(trans)
class TextFormatData(object): """Encapsulates all settings in the Fonts & Colors page for a scheme.""" def __init__(self, scheme): """Loads the data from scheme.""" self.font = None self.baseColors = {} self.defaultStyles = {} self.allStyles = {} self._inherits = {} self.load(scheme) def load(self, scheme): """Load the settings for the scheme. Called on init.""" s = QSettings() s.beginGroup("fontscolors/" + scheme) # load font defaultfont = "Lucida Console" if os.name == "nt" else "monospace" self.font = QFont(s.value("fontfamily", defaultfont, str)) self.font.setPointSizeF(s.value("fontsize", 10.0, float)) # load base colors s.beginGroup("basecolors") for name in baseColors: if s.contains(name): self.baseColors[name] = QColor(s.value(name, "", str)) else: self.baseColors[name] = baseColorDefaults[name]() s.endGroup() # get the list of supported styles from ly.colorize all_styles = ly.colorize.default_mapping() default_styles = set() for group, styles in all_styles: d = self._inherits[group] = {} for style in styles: if style.base: default_styles.add(style.base) d[style.name] = style.base default_scheme = ly.colorize.default_scheme # load default styles s.beginGroup("defaultstyles") for name in default_styles: self.defaultStyles[name] = f = QTextCharFormat() css = default_scheme[None].get(name) if css: css2fmt(css, f) s.beginGroup(name) self.loadTextFormat(f, s) s.endGroup() s.endGroup() # load specific styles s.beginGroup("allstyles") for group, styles in all_styles: self.allStyles[group]= {} s.beginGroup(group) for style in styles: self.allStyles[group][style.name] = f = QTextCharFormat() css = default_scheme[group].get(style.name) if css: css2fmt(css, f) s.beginGroup(style.name) self.loadTextFormat(f, s) s.endGroup() s.endGroup() s.endGroup() def save(self, scheme): """Save the settings to the scheme.""" s = QSettings() s.beginGroup("fontscolors/" + scheme) # save font s.setValue("fontfamily", self.font.family()) s.setValue("fontsize", self.font.pointSizeF()) # save base colors for name in baseColors: s.setValue("basecolors/"+name, self.baseColors[name].name()) # save default styles s.beginGroup("defaultstyles") for name in defaultStyles: s.beginGroup(name) self.saveTextFormat(self.defaultStyles[name], s) s.endGroup() s.endGroup() # save all specific styles s.beginGroup("allstyles") for group, styles in ly.colorize.default_mapping(): s.beginGroup(group) for style in styles: s.beginGroup(style.name) self.saveTextFormat(self.allStyles[group][style.name], s) s.endGroup() s.endGroup() s.endGroup() def textFormat(self, group, name): """Return a QTextCharFormat() for the specified group and name.""" inherit = self._inherits[group].get(name) f = QTextCharFormat(self.defaultStyles[inherit]) if inherit else QTextCharFormat() f.merge(self.allStyles[group][name]) return f def css_scheme(self): """Return a dictionary of css dictionaries representing this scheme. This can be fed to the ly.colorize.format_stylesheet() function. """ scheme = {} # base/default styles d = scheme[None] = {} for name, fmt in self.defaultStyles.items(): d[name] = fmt2css(fmt) # mode/group styles for mode, styles in self.allStyles.items(): d = scheme[mode] = {} for name, fmt in styles.items(): d[name] = fmt2css(fmt) return scheme def palette(self): """Return a basic palette with text, background, selection and selection background filled in.""" p = QApplication.palette() p.setColor(QPalette.Text, self.baseColors['text']) p.setColor(QPalette.Base, self.baseColors['background']) p.setColor(QPalette.HighlightedText, self.baseColors['selectiontext']) p.setColor(QPalette.Highlight, self.baseColors['selectionbackground']) return p def saveTextFormat(self, fmt, settings): """(Internal) Store one QTextCharFormat in the QSettings instance.""" if fmt.hasProperty(QTextFormat.FontWeight): settings.setValue('bold', fmt.fontWeight() >= 70) else: settings.remove('bold') if fmt.hasProperty(QTextFormat.FontItalic): settings.setValue('italic', fmt.fontItalic()) else: settings.remove('italic') if fmt.hasProperty(QTextFormat.TextUnderlineStyle): settings.setValue('underline', fmt.fontUnderline()) else: settings.remove('underline') if fmt.hasProperty(QTextFormat.ForegroundBrush): settings.setValue('textColor', fmt.foreground().color().name()) else: settings.remove('textColor') if fmt.hasProperty(QTextFormat.BackgroundBrush): settings.setValue('backgroundColor', fmt.background().color().name()) else: settings.remove('backgroundColor') if fmt.hasProperty(QTextFormat.TextUnderlineColor): settings.setValue('underlineColor', fmt.underlineColor().name()) else: settings.remove('underlineColor') def loadTextFormat(self, fmt, settings): """(Internal) Merge values from the QSettings instance into the QTextCharFormat.""" if settings.contains('bold'): fmt.setFontWeight(QFont.Bold if settings.value('bold', False, bool) else QFont.Normal) if settings.contains('italic'): fmt.setFontItalic(settings.value('italic', False, bool)) if settings.contains('underline'): fmt.setFontUnderline(settings.value('underline', False, bool)) if settings.contains('textColor'): fmt.setForeground(QColor(settings.value('textColor', '' , str))) if settings.contains('backgroundColor'): fmt.setBackground(QColor(settings.value('backgroundColor', '' , str))) if settings.contains('underlineColor'): fmt.setUnderlineColor(QColor(settings.value('underlineColor', '' , str)))
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 Window(QMainWindow, WinUi): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setupUi(self) self.textEdit.textChanged.connect(self.paintText) self.textAngle.valueChanged.connect(self.paintText) self.textOpacity.valueChanged.connect(self.paintText) self.fontSize.valueChanged.connect(self.paintText) self.tilingBox.toggled.connect(self.paintText) self.staggeredBox.toggled.connect(self.paintText) self.boldBox.toggled.connect(self.paintText) self.widthSpacing.valueChanged.connect(self.paintText) self.heightSpacing.valueChanged.connect(self.paintText) self.color = QColor(0, 0, 0) effect = QGraphicsColorizeEffect() effect.setColor(self.color) self.colorButton.setGraphicsEffect(effect) self.font = QFont("Serif", 32) self.fontButton.setText(self.font.family()) self.images = [] self.lastPath = Path.cwd() self.zoom = Decimal(1) @Slot() def on_colorButton_clicked(self): new = QColorDialog.getColor(self.color, self) if not new.isValid(): return self.color = new effect = QGraphicsColorizeEffect() effect.setColor(self.color) self.colorButton.setGraphicsEffect(effect) self.paintText() @Slot() def on_fontButton_clicked(self): font, valid = QFontDialog.getFont(self.font, self) if not valid: return self.font = font self.fontButton.setText(self.font.family()) self.fontSize.setValue(self.font.pointSize()) self.paintText() @Slot() def on_actionSave_triggered(self): if not self.images: return path, _ = QFileDialog.getSaveFileName( self, self.tr("Save image"), str(self.lastPath), self.tr("Images (*.png *.jpg *.jpeg);;PDF (*.pdf)"), ) if not path: return path = Path(path) self.lastPath = path.parent if path.suffix == ".pdf": self.saveAsPdf(path) else: self.saveAsImages(path) def saveAsImages(self, path): if len(self.images) == 1: target = self.images[0].copy() self.paintOn(target) target.save(str(path)) else: path = Path(path) for n, source in enumerate(self.images, 1): target = source.copy() self.paintOn(target) target.save(f"{path.parent}/{path.stem}-{n:02d}{path.suffix}") def saveAsPdf(self, path): pdf = QPrinter() pdf.setFullPage(True) pdf.setOutputFileName(str(path)) first = True painter = QPainter() for source in self.images: marked = source.copy() self.paintOn(marked) pdf.setPageSize(QPageSize(marked.size())) if first: first = False painter.begin(pdf) else: pdf.newPage() # though we set page size, the rect is not the same rect = marked.rect() rect.setWidth(pdf.width()) rect.setHeight(pdf.height()) painter.drawImage(rect, marked) painter.end() @Slot() def on_actionOpen_triggered(self): path, _ = QFileDialog.getOpenFileName( self, self.tr("Open image"), str(self.lastPath), self.tr("Images/PDF (*.png *.jpg *.jpeg *.pdf)"), ) if not path: return self.lastPath = Path(path).parent self.loadFile(path) def loadFile(self, path): if path.endswith(".pdf"): self.loadPdf(path) else: self.loadImage(path) def loadImage(self, path): self.addImage(QImage(path)) def addImage(self, image): self.images.append(image) layout = self.imagesContainer.layout() layout.addWidget(QLabel(parent=self.imagesContainer)) self.paintTextImage(layout.count() - 1) def loadPdf(self, path): doc = Poppler.Document.load(path) page = doc.page(0) dlg = ResolutionDialog(page.pageSize(), file=path, parent=self) dlg.exec() res = dlg.intValue() for i in range(doc.numPages()): page = doc.page(i) image = page.renderToImage(res, res) self.addImage(image) def getImageWidget(self, i): return self.imagesContainer.layout().itemAt(i).widget() @Slot() def paintText(self): for i in range(self.imagesContainer.layout().count()): self.paintTextImage(i) def paintTextImage(self, i): if not self.images: return source = self.images[i] target = source.copy() self.paintOn(target) target = target.scaled(target.size() * self.zoom, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) self.getImageWidget(i).setPixmap(QPixmap(target)) def paintOn(self, device): painter = QPainter(device) self.font.setPointSize(self.fontSize.value()) self.font.setBold(self.boldBox.isChecked()) painter.setFont(self.font) self.color.setAlpha(self.textOpacity.value()) painter.setPen(QPen(self.color)) text = self.textEdit.toPlainText() box = painter.boundingRect(device.rect(), Qt.AlignCenter, text) transform = QTransform() center = box.center() transform.translate(center.x(), center.y()) transform.rotate(self.textAngle.value()) transform.translate(-center.x(), -center.y()) def paintWith(tileform): combined = tileform * transform if not combined.mapRect(box).intersects(device.rect()): return False painter.setTransform(combined) painter.drawText(box, Qt.AlignCenter, text) return True def paintTile(x, y): tile = QTransform() stagger = 0 if y % 2 and self.staggeredBox.isChecked(): stagger = 0.5 tile.translate( (stagger + x) * (box.width() + metrics.horizontalAdvance(" ") * self.widthSpacing.value() / 100), y * (box.height() + metrics.lineSpacing() * self.heightSpacing.value() / 100), ) return paintWith(tile) # paint on center paintWith(QTransform()) if self.tilingBox.isChecked(): # paint tiles with increasing distance # xxxxx # x...x # x.o.x # x...x # xxxxx metrics = QFontMetricsF(self.font) for radius in range(1, 1000): has_painted = False for x in range(-radius, radius + 1): has_painted = paintTile(x, -radius) or has_painted has_painted = paintTile(x, radius) or has_painted for y in range(-radius + 1, radius): has_painted = paintTile(-radius, y) or has_painted has_painted = paintTile(radius, y) or has_painted if not has_painted: # everything was out of bounds, so will the next radius break painter.end() @Slot() def on_actionZoomOriginal_triggered(self): self.zoom = Decimal("1") self.paintText() @Slot() def on_actionZoomIn_triggered(self): self.zoom *= Decimal("1.5") self.paintText() @Slot() def on_actionZoomOut_triggered(self): self.zoom /= Decimal("1.5") self.paintText()
def _get_font(self): font = QFont("consolas", 11) if LINUX: font = QFont("monospace", 12) return font.family(), font.pointSize()
class CharactersMapWidget(QWidget): """ docstring for CharactersMapWidget """ characterSelected = pyqtSignal(str) def __init__(self, parent=None): super(CharactersMapWidget, self).__init__(parent) self.displayFont = QFont() self.cellSize = 24 self.columns = 16 self.lastKey = -1 self.charSet = None self.setMouseTracking(True) def setCharSet(self, charSet): self.charSet = charSet self.update() def updateFont(self, fontFamily): self.displayFont.setFamily(fontFamily) self.update() def sizeHint(self): if self.charSet != None: ln = len(self.charSet)+1 else: ln = 192 return QSize( self.columns * self.cellSize, (ln / self.columns) * self.cellSize ) def mouseMoveEvent(self, event): position = self.mapFromGlobal(event.globalPos()) key = (position.y() // self.cellSize) * self.columns + position.x() // self.cellSize text = '<p>Character: <span style="font-size: 24pt; font-family: %s">%s</span><p>code: %d' % ( self.displayFont.family(), self._chr(key), key+32) QToolTip.showText(event.globalPos(), text, self) def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.lastKey = (event.y() // self.cellSize) * self.columns + event.x() // self.cellSize key_ch = self._chr(self.lastKey) self.characterSelected.emit(key_ch) self.update() else: super(CharactersMapWidget, 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.cellSize endRow = redrawRect.bottom() // self.cellSize beginColumn = redrawRect.left() // self.cellSize endColumn = redrawRect.right() // self.cellSize # grid painter.setPen(Qt.gray) for row in range(beginRow, endRow + 1): for column in range(beginColumn, endColumn + 1): painter.drawRect(column * self.cellSize, row * self.cellSize, self.cellSize, self.cellSize) 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.cellSize, row * self.cellSize, self.cellSize, self.cellSize) if key == self.lastKey: painter.fillRect(column * self.cellSize + 1, row * self.cellSize + 1, self.cellSize, self.cellSize, Qt.red) key_ch = self._chr(key) painter.drawText(column * self.cellSize + (self.cellSize / 2) - fontMetrics.width(key_ch) / 2, row * self.cellSize + 4 + fontMetrics.ascent(), key_ch) def _chr(self, codepoint): if self.charSet != None and codepoint < len(self.charSet): return self.charSet[ codepoint ] else: return None def reset(self): self.lastKey = None self.characterSelected.emit( '' ) self.update()
def __init__(self, parent=None): super().__init__(parent) self.settings = QSettings() self.settings.beginGroup("plugins/layertreeicons") self.setWindowTitle(self.tr("Default layer tree properties")) self.setMinimumSize(QSize(250, 0)) layout = QVBoxLayout(self) form_layout = QFormLayout() hlayout = QHBoxLayout() self.group_font_label = QLabel("") group_font_button = QToolButton(self) group_font_button.setText("...") hlayout.addWidget(self.group_font_label) hlayout.addWidget(group_font_button) form_layout.addRow(self.tr("Group node font"), hlayout) group_font_button.setToolTip("Select font") group_font_button.clicked.connect(self.select_group_font) hlayout = QHBoxLayout() self.layer_font_label = QLabel("") layer_font_button = QToolButton(self) layer_font_button.setText("...") hlayout.addWidget(self.layer_font_label) hlayout.addWidget(layer_font_button) form_layout.addRow(self.tr("Layer node font"), hlayout) layer_font_button.setToolTip("Select font") layer_font_button.clicked.connect(self.select_layer_font) self.icon_size_combo = QComboBox(self) self.icon_size_combo.addItem(self.tr("default"), -1) for val in (16, 24, 32, 48, 64): self.icon_size_combo.addItem(f"{val} px", val) idx = self.icon_size_combo.findData(self.settings.value("iconsize", -1, int)) self.icon_size_combo.setCurrentIndex(idx) self.icon_size_combo.currentIndexChanged.connect(self.on_icon_size_changed) form_layout.addRow(self.tr("Icon Size"), self.icon_size_combo) layout.addLayout(form_layout) group_box = QGroupBox(self) group_box.setTitle("Default Icons") self.form_layout = QFormLayout(group_box) layout.addWidget(group_box) self.reset_button = QPushButton(self.tr("Reset default properties")) layout.addWidget(self.reset_button) self.reset_button.clicked.connect(self.reset_all) self.resource_browser = ResourceBrowser(parent) self.source_data = { "group": (self.tr("Group"), ":/images/themes/default/mActionFolder.svg",), "raster": (self.tr("Raster"), ":/images/themes/default/mIconRaster.svg",), "point": (self.tr("Point"), ":/images/themes/default/mIconPointLayer.svg",), "line": (self.tr("Line"), ":/images/themes/default/mIconLineLayer.svg",), "polygon": ( self.tr("Polygon"), ":/images/themes/default/mIconPolygonLayer.svg", ), "nogeometry": ( self.tr("No Geometry"), ":/images/themes/default/mIconTableLayer.svg", ), } if Qgis.QGIS_VERSION_INT > 30200: self.source_data["mesh"] = ( self.tr("Mesh Layer"), ":/images/themes/default/mIconMeshLayer.svg", ) for settings_key, (text, default_icon) in self.source_data.items(): button = QToolButton(self) button.setObjectName(settings_key) button.setPopupMode(QToolButton.MenuButtonPopup) button.setIconSize(QSize(24, 24)) button.setIcon(QIcon(default_icon)) label = QLabel(text, self) label.setMinimumSize(QSize(label.minimumSize().width(), 38)) self.form_layout.addRow(label, button) action_from_qgis = QAction("Set from QGIS ressources", button) action_from_qgis.triggered.connect( partial(self.set_icon_from_ressources, settings_key) ) button.addAction(action_from_qgis) button.clicked.connect(action_from_qgis.trigger) action_from_file = QAction("Set from file", button) action_from_file.triggered.connect( partial(self.set_icon_from_file, settings_key) ) button.addAction(action_from_file) action_reset = QAction("Reset", button) action_reset.triggered.connect(partial(self.reset, settings_key)) button.addAction(action_reset) f = QFont() if f.fromString(self.settings.value("group_font")) and f.family(): iface.layerTreeView().layerTreeModel().setLayerTreeNodeFont( QgsLayerTree.NodeGroup, f ) else: iface.layerTreeView().layerTreeModel().setLayerTreeNodeFont( QgsLayerTree.NodeGroup, iface.layerTreeView().font() ) self.settings.setValue( "group_font", iface.layerTreeView().font().toString() ) f = QFont() if f.fromString(self.settings.value("layer_font")) and f.family(): iface.layerTreeView().layerTreeModel().setLayerTreeNodeFont( QgsLayerTree.NodeLayer, f ) else: f = iface.layerTreeView().font() f.setBold(True) iface.layerTreeView().layerTreeModel().setLayerTreeNodeFont( QgsLayerTree.NodeLayer, f ) self.settings.setValue("layer_font", f.toString()) self.update_font_labels()
class CharactersMapWidget(QWidget): """ docstring for CharactersMapWidget """ characterSelected = pyqtSignal(str) def __init__(self, parent=None): super(CharactersMapWidget, self).__init__(parent) self.displayFont = QFont() self.cellSize = 24 self.columns = 16 self.lastKey = -1 self.charSet = None self.setMouseTracking(True) def setCharSet(self, charSet): self.charSet = charSet self.update() def updateFont(self, fontFamily): self.displayFont.setFamily(fontFamily) self.update() def sizeHint(self): if self.charSet != None: ln = len(self.charSet) + 1 else: ln = 192 return QSize(self.columns * self.cellSize, (ln / self.columns) * self.cellSize) def mouseMoveEvent(self, event): position = self.mapFromGlobal(event.globalPos()) key = (position.y() // self.cellSize) * self.columns + position.x() // self.cellSize text = '<p>Character: <span style="font-size: 24pt; font-family: %s">%s</span><p>code: %d' % ( self.displayFont.family(), self._chr(key), key + 32) QToolTip.showText(event.globalPos(), text, self) def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.lastKey = (event.y() // self.cellSize ) * self.columns + event.x() // self.cellSize key_ch = self._chr(self.lastKey) self.characterSelected.emit(key_ch) self.update() else: super(CharactersMapWidget, 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.cellSize endRow = redrawRect.bottom() // self.cellSize beginColumn = redrawRect.left() // self.cellSize endColumn = redrawRect.right() // self.cellSize # grid painter.setPen(Qt.gray) for row in range(beginRow, endRow + 1): for column in range(beginColumn, endColumn + 1): painter.drawRect(column * self.cellSize, row * self.cellSize, self.cellSize, self.cellSize) 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.cellSize, row * self.cellSize, self.cellSize, self.cellSize) if key == self.lastKey: painter.fillRect(column * self.cellSize + 1, row * self.cellSize + 1, self.cellSize, self.cellSize, Qt.red) key_ch = self._chr(key) painter.drawText( column * self.cellSize + (self.cellSize / 2) - fontMetrics.width(key_ch) / 2, row * self.cellSize + 4 + fontMetrics.ascent(), key_ch) def _chr(self, codepoint): if self.charSet != None and codepoint < len(self.charSet): return self.charSet[codepoint] else: return None def reset(self): self.lastKey = None self.characterSelected.emit('') self.update()
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)
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)
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 editor._themeData = themeDatas editor.highlighter.updateColorScheme()
class TextFormatData(object): """Encapsulates all settings in the Fonts & Colors page for a scheme.""" def __init__(self, scheme): """Loads the data from scheme.""" self.font = None self.baseColors = {} self.defaultStyles = {} self.allStyles = {} self._inherits = {} self.load(scheme) def load(self, scheme): """Load the settings for the scheme. Called on init.""" s = QSettings() s.beginGroup("fontscolors/" + scheme) # load font defaultfont = "Lucida Console" if os.name == "nt" else "monospace" self.font = QFont(s.value("fontfamily", defaultfont, str)) self.font.setPointSizeF(s.value("fontsize", 10.0, float)) # load base colors s.beginGroup("basecolors") for name in baseColors: if s.contains(name): self.baseColors[name] = QColor(s.value(name, "", str)) else: self.baseColors[name] = baseColorDefaults[name]() s.endGroup() # get the list of supported styles from ly.colorize all_styles = ly.colorize.default_mapping() default_styles = set() for group, styles in all_styles: d = self._inherits[group] = {} for style in styles: if style.base: default_styles.add(style.base) d[style.name] = style.base default_scheme = ly.colorize.default_scheme # load default styles s.beginGroup("defaultstyles") for name in default_styles: self.defaultStyles[name] = f = QTextCharFormat() css = default_scheme[None].get(name) if css: css2fmt(css, f) s.beginGroup(name) self.loadTextFormat(f, s) s.endGroup() s.endGroup() # load specific styles s.beginGroup("allstyles") for group, styles in all_styles: self.allStyles[group] = {} s.beginGroup(group) for style in styles: self.allStyles[group][style.name] = f = QTextCharFormat() css = default_scheme[group].get(style.name) if css: css2fmt(css, f) s.beginGroup(style.name) self.loadTextFormat(f, s) s.endGroup() s.endGroup() s.endGroup() def save(self, scheme): """Save the settings to the scheme.""" s = QSettings() s.beginGroup("fontscolors/" + scheme) # save font s.setValue("fontfamily", self.font.family()) s.setValue("fontsize", self.font.pointSizeF()) # save base colors for name in baseColors: s.setValue("basecolors/" + name, self.baseColors[name].name()) # save default styles s.beginGroup("defaultstyles") for name in defaultStyles: s.beginGroup(name) self.saveTextFormat(self.defaultStyles[name], s) s.endGroup() s.endGroup() # save all specific styles s.beginGroup("allstyles") for group, styles in ly.colorize.default_mapping(): s.beginGroup(group) for style in styles: s.beginGroup(style.name) self.saveTextFormat(self.allStyles[group][style.name], s) s.endGroup() s.endGroup() s.endGroup() def textFormat(self, group, name): """Return a QTextCharFormat() for the specified group and name.""" inherit = self._inherits[group].get(name) f = QTextCharFormat( self.defaultStyles[inherit]) if inherit else QTextCharFormat() f.merge(self.allStyles[group][name]) return f def css_scheme(self): """Return a dictionary of css dictionaries representing this scheme. This can be fed to the ly.colorize.format_stylesheet() function. """ scheme = {} # base/default styles d = scheme[None] = {} for name, fmt in self.defaultStyles.items(): d[name] = fmt2css(fmt) # mode/group styles for mode, styles in self.allStyles.items(): d = scheme[mode] = {} for name, fmt in styles.items(): d[name] = fmt2css(fmt) return scheme def palette(self): """Return a basic palette with text, background, selection and selection background filled in.""" p = QApplication.palette() p.setColor(QPalette.Text, self.baseColors['text']) p.setColor(QPalette.Base, self.baseColors['background']) p.setColor(QPalette.HighlightedText, self.baseColors['selectiontext']) p.setColor(QPalette.Highlight, self.baseColors['selectionbackground']) return p def saveTextFormat(self, fmt, settings): """(Internal) Store one QTextCharFormat in the QSettings instance.""" if fmt.hasProperty(QTextFormat.FontWeight): settings.setValue('bold', fmt.fontWeight() >= 70) else: settings.remove('bold') if fmt.hasProperty(QTextFormat.FontItalic): settings.setValue('italic', fmt.fontItalic()) else: settings.remove('italic') if fmt.hasProperty(QTextFormat.TextUnderlineStyle): settings.setValue('underline', fmt.fontUnderline()) else: settings.remove('underline') if fmt.hasProperty(QTextFormat.ForegroundBrush): settings.setValue('textColor', fmt.foreground().color().name()) else: settings.remove('textColor') if fmt.hasProperty(QTextFormat.BackgroundBrush): settings.setValue('backgroundColor', fmt.background().color().name()) else: settings.remove('backgroundColor') if fmt.hasProperty(QTextFormat.TextUnderlineColor): settings.setValue('underlineColor', fmt.underlineColor().name()) else: settings.remove('underlineColor') def loadTextFormat(self, fmt, settings): """(Internal) Merge values from the QSettings instance into the QTextCharFormat.""" if settings.contains('bold'): fmt.setFontWeight(QFont.Bold if settings. value('bold', False, bool) else QFont.Normal) if settings.contains('italic'): fmt.setFontItalic(settings.value('italic', False, bool)) if settings.contains('underline'): fmt.setFontUnderline(settings.value('underline', False, bool)) if settings.contains('textColor'): fmt.setForeground(QColor(settings.value('textColor', '', str))) if settings.contains('backgroundColor'): fmt.setBackground( QColor(settings.value('backgroundColor', '', str))) if settings.contains('underlineColor'): fmt.setUnderlineColor( QColor(settings.value('underlineColor', '', str)))
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)
def llenar_tabla_lote(self): fuente_negrita = QFont() print(fuente_negrita.family()) #fuente_negrita.setBold(True) item_lotes = QTableWidgetItem("Lote") item_lotes.setFont(fuente_negrita) item_empresas = QTableWidgetItem("Empresa") item_empresas.setFont(fuente_negrita) item_ofertas = QTableWidgetItem("Oferta") item_ofertas.setFont(fuente_negrita) item_descuentos = QTableWidgetItem("Descuento") item_descuentos.setFont(fuente_negrita) item_ofertas_finales = QTableWidgetItem("Oferta Final") item_ofertas_finales.setFont(fuente_negrita) self.tabla_lote.setItem(0, 0, item_lotes) self.tabla_lote.setItem(1, 0, item_empresas) self.tabla_lote.setItem(2, 0, item_ofertas) self.tabla_lote.setItem(3, 0, item_descuentos) self.tabla_lote.setItem(4, 0, item_ofertas_finales) for lote in self.licitacion.lotes: self.tabla_lote.setColumnCount(self.tabla_lote.columnCount() + 1) columna = self.tabla_lote.columnCount() - 1 item_lote = QTableWidgetItem(lote.obtener_descripcion()) item_lote.setTextAlignment(Qt.AlignCenter) self.tabla_lote.setItem(0, columna, item_lote) for posibilidad in self.licitacion.combinacion_ganadora( ).posibilidades: if posibilidad.lote_contenido(lote): for oferta in posibilidad.conjunto_ofertas.ofertas: if oferta.lote == lote: item_empresa = QTableWidgetItem( oferta.empresa.nombre) item_empresa.setTextAlignment(Qt.AlignCenter) self.tabla_lote.setItem(1, columna, item_empresa) item_oferta = QTableWidgetItem("{0:,.3f}".format( oferta.valor)) item_oferta.setTextAlignment(Qt.AlignCenter) self.tabla_lote.setItem(2, columna, item_oferta) if posibilidad.adicional.es_nulo( ) or not posibilidad.adicional.conjunto_ofertas.oferta_contenida( oferta): item_descuento = QTableWidgetItem( "{0:.3f}%".format(0)) item_descuento.setTextAlignment(Qt.AlignCenter) self.tabla_lote.setItem( 3, columna, item_descuento) item_oferta_final = QTableWidgetItem( "{0:,.3f}".format(oferta.valor)) item_oferta_final.setTextAlignment( Qt.AlignCenter) self.tabla_lote.setItem( 4, columna, item_oferta_final) else: item_descuento = QTableWidgetItem( "{0:.2f}%".format( abs(posibilidad.adicional.porcentaje))) item_descuento.setTextAlignment(Qt.AlignCenter) self.tabla_lote.setItem( 3, columna, item_descuento) item_oferta_final = QTableWidgetItem( "{0:,.3f}".format(oferta.valor + posibilidad.adicional. valor_en_oferta(oferta))) item_oferta_final.setTextAlignment( Qt.AlignCenter) self.tabla_lote.setItem( 4, columna, item_oferta_final) break break
class NFontConverterWidget(QWidget): data_ready_signal = pyqtSignal(NGL_Font) def __init__(self, name, dataSlot=None, parent=None): """ Constructor """ super(NFontConverterWidget, self).__init__(parent) self.settings = QSettings('NeilLab', 'NGL Font') # load main ui window uifile = pkg_resources.resource_filename('ngl_utils.nfont', 'qtres/ngl_font.ui') self.uic = uic.loadUi(uifile, self) self.nfont_view = CodeView_Window(self) self.sysFont_dialog = QFontDialog(self) # def sysfont and font name self.font = QFont('Times', 8) self.NGL_Font = None fname = NGL_Font.formatName(self.font.family(), self.font.pointSize(), self.font.bold()) self.lineEdit_fontName.setText(fname) # generates chars set for combobox self._charstersRangesInit() # font edit widget self.edit_view = NFontEditWidget('__util__') # connect signals / slots self.tBtn_Font.clicked.connect(self._selectFont_slot) self.tBtn_AddChars.clicked.connect(self._add_chars_slot) self.tBtn_Convert.clicked.connect(self._convert_slot) self.tBtn_Save.clicked.connect(self._saveAs_slot) self.tBtn_ViewOut.clicked.connect(self._view_out_slot) self.tBtn_Edit.clicked.connect(self._edit_font_slot) if name == '__main__': self.tBtn_Close.setText('Close') self.tBtn_Close.clicked.connect(self._close_slot) else: self.tBtn_Close.setText('Add') self.tBtn_Close.clicked.connect(self._ok_slot) self.connectDataReadySlot(dataSlot) # set window to center and show self.frameGeometry().moveCenter( QDesktopWidget().availableGeometry().center()) def connectDataReadySlot(self, dataSlot): """ dataSlot is Qt slot for signaling converting ready state """ if dataSlot: self.data_ready_signal.connect(dataSlot) def _charstersRangesInit(self): """ Init charsters sets ranges """ cm_chr = self.cmBox_chars_sets cm_chr.insertItem(0, 'Full eng', ''.join([chr(x) for x in range(ord(' '), ord('~'))])) cm_chr.insertItem(1, 'Upper eng (A-Z)', ''.join([chr(x) for x in range(ord('A'), ord('Z'))])) cm_chr.insertItem(2, 'Lower eng (a-z)', ''.join([chr(x) for x in range(ord('a'), ord('z'))])) cm_chr.insertItem( 3, 'Full rus', ''.join([chr(x) for x in range(ord(u'А'), ord(u'я'))])) cm_chr.insertItem( 4, 'Upper rus (А-Я)', ''.join([chr(x) for x in range(ord(u'А'), ord(u'Я'))])) cm_chr.insertItem(5, 'Lower rus (а-я)', ''.join([chr(x) for x in range(ord('а'), ord('я'))])) cm_chr.insertItem(6, 'Full eng+rus', cm_chr.itemData(0) + cm_chr.itemData(3)) cm_chr.insertItem(7, 'Numbers (0-9)', '0123456789') @pyqtSlot() def _selectFont_slot(self): """ Select Font slot """ font, font_res = self.sysFont_dialog.getFont(self.font, None, 'Select Font') if font_res: name = NGL_Font.formatName(font.family(), font.pointSize(), font.bold()) self.lineEdit_fontName.setText(name) self.font = font @pyqtSlot() def _add_chars_slot(self): """ Add charsers sets to textBrowser """ self.txtBrowser_chars.clear() chars_sets = self.cmBox_chars_sets.currentData() self.txtBrowser_chars.insertPlainText(chars_sets) @pyqtSlot() def _convert_slot(self): """ Start converting slot """ chars_sets = str(self.txtBrowser_chars.toPlainText()) if chars_sets: gtime = time.time() # converting to ngl font name = self.lineEdit_fontName.text() self.NGL_Font = NFontConverter.convertQFont( chars_sets, name, self.font) ch_list = self.NGL_Font.get_chars_list() gtime = time.time() - gtime self.lbl_gen_time.setText( 'converted at: %.2f sec | estimate code size: ~%0.3fk' % (gtime, self.NGL_Font.code_size_calc() / 1000)) self.lbl_gen_time.update() else: QMessageBox.critical( self, 'ERROR', """ Nothing to convert! Add singles char or characters set to textbox first""") @pyqtSlot() def _view_out_slot(self, nfont=None): """ View converting out code """ if nfont == None: self.nfont_view.view(self.NGL_Font) else: self.nfont_view.view(nfont) @pyqtSlot() def _edit_font_slot(self): odir = self.settings.value('open_last_dir', type=str) if not odir: odir = './' fileName, _ = QFileDialog.getOpenFileName( self, "Open NGL Font source for edit", odir, "Source ngl font Files (*.c);;All Files (*)", options=QFileDialog.DontUseNativeDialog) if fileName: self.settings.setValue('open_last_dir', os.path.dirname(fileName)) # set parsed ngl font and show edit widget self.edit_view.setFontFile(fileName) self.edit_view.show() def _save(self, filepath, font): with open(filepath, 'w') as f: f.write(font.get_code().replace('\r\n', '\n')) @pyqtSlot() def _saveAs_slot(self): """ Save out to file """ if self.NGL_Font: file_name, sts = QFileDialog.getSaveFileName( self, "QFileDialog.getSaveFileName()", self.NGL_Font.name, "C files (*.c)", options=QFileDialog.Options() | QFileDialog.DontUseNativeDialog) if sts: self._save(file_name + '.c', self.NGL_Font) @pyqtSlot() def _ok_slot(self): if self.NGL_Font: self.data_ready_signal.emit(self.NGL_Font) else: QMessageBox.critical(self, 'ERROR', 'Font not convert!') @pyqtSlot() def _close_slot(self): self.close() def keyPressEvent(self, e): if e.key() == Qt.Key_Escape: self._close_slot()
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"]) 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 "", ) ) # 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 heriting 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.setMisspelledColor(QColor(opt["misspelled"])) self.highlighter.setDefaultCharFormat(self._defaultCharFormat) self.highlighter.setDefaultBlockFormat(self._defaultBlockFormat)
def nodecondole_font(self, font): font = QFont(font.family(), self.spinBox_ConsoleFontSize.value()) self.nodeconsole_set_font(font)