class CharMap(preferences.Group): def __init__(self, page): super(CharMap, self).__init__(page) layout = QVBoxLayout() self.setLayout(layout) self.fontLabel = QLabel() self.fontChooser = QFontComboBox(currentFontChanged=self.changed) self.fontSize = QDoubleSpinBox(valueChanged=self.changed) self.fontSize.setRange(6.0, 32.0) self.fontSize.setSingleStep(0.5) self.fontSize.setDecimals(1) box = QHBoxLayout() box.addWidget(self.fontLabel) box.addWidget(self.fontChooser, 1) box.addWidget(self.fontSize) layout.addLayout(box) app.translateUI(self) def translateUI(self): self.setTitle(_("Special Characters")) self.fontLabel.setText(_("Font:")) def loadSettings(self): s = QSettings() s.beginGroup("charmaptool") font = self.font() family = s.value("fontfamily", "", str) if family: font.setFamily(family) font.setPointSizeF(s.value("fontsize", font.pointSizeF(), float)) with qutil.signalsBlocked(self.fontChooser, self.fontSize): self.fontChooser.setCurrentFont(font) self.fontSize.setValue(font.pointSizeF()) def saveSettings(self): s = QSettings() s.beginGroup("charmaptool") s.setValue("fontfamily", self.fontChooser.currentFont().family()) s.setValue("fontsize", self.fontSize.value())
class FontLayout(QGridLayout): """Font selection""" def __init__(self, value, parent=None): QGridLayout.__init__(self) font = tuple_to_qfont(value) assert font is not None # Font family self.family = QFontComboBox(parent) self.family.setCurrentFont(font) self.addWidget(self.family, 0, 0, 1, -1) # Font size self.size = QComboBox(parent) self.size.setEditable(True) sizelist = list(range(6, 12)) + list(range(12, 30, 2)) + [36, 48, 72] size = font.pointSize() if size not in sizelist: sizelist.append(size) sizelist.sort() self.size.addItems([str(s) for s in sizelist]) self.size.setCurrentIndex(sizelist.index(size)) self.addWidget(self.size, 1, 0) # Italic or not self.italic = QCheckBox(self.tr("Italic"), parent) self.italic.setChecked(font.italic()) self.addWidget(self.italic, 1, 1) # Bold or not self.bold = QCheckBox(self.tr("Bold"), parent) self.bold.setChecked(font.bold()) self.addWidget(self.bold, 1, 2) def get_font(self): font = self.family.currentFont() font.setItalic(self.italic.isChecked()) font.setBold(self.bold.isChecked()) font.setPointSize(int(self.size.currentText())) return qfont_to_tuple(font)
def context_menu(self): menu = QMenu() font_box = QFontComboBox() font_box.setCurrentFont(self.post_text_font) font_box.currentFontChanged.connect( lambda: self.set_post_text_font(font=font_box.currentFont())) font_box.currentFontChanged.connect(menu.close) font_box_label = QLabel('Font:') layout = QHBoxLayout() layout.addWidget(font_box_label) layout.addWidget(font_box) font_box_widget = QWidget(self) font_box_widget.setLayout(layout) font_box_item = QWidgetAction(self) font_box_item.setDefaultWidget(font_box_widget) font_size_box = QComboBox() font_size_box.addItems(str(x) for x in range(4, 30)) font_size_box.setCurrentText(str(self.post_text_font_size)) font_size_label = QLabel('Font Size:') size_layout = QHBoxLayout() size_layout.addWidget(font_size_label) size_layout.addWidget(font_size_box) font_size_widget = QWidget(self) font_size_widget.setLayout(size_layout) font_size_box.currentIndexChanged.connect( lambda: self.set_post_text_font(size=int(font_size_box.currentText( )))) font_size_box.currentIndexChanged.connect(menu.close) font_size_item = QWidgetAction(self) font_size_item.setDefaultWidget(font_size_widget) menu.addAction(font_box_item) menu.addAction(font_size_item) menu.addSeparator() if not self.stand_alone: menu.addAction('Detach Text Box', lambda: self.detach_signal.emit()) menu.exec_(QCursor.pos())
class LogTool(preferences.Group): def __init__(self, page): super(LogTool, self).__init__(page) layout = QVBoxLayout() self.setLayout(layout) self.fontLabel = QLabel() self.fontChooser = QFontComboBox(currentFontChanged=self.changed) self.fontSize = QDoubleSpinBox(valueChanged=self.changed) self.fontSize.setRange(6.0, 32.0) self.fontSize.setSingleStep(0.5) self.fontSize.setDecimals(1) box = QHBoxLayout() box.addWidget(self.fontLabel) box.addWidget(self.fontChooser, 1) box.addWidget(self.fontSize) layout.addLayout(box) self.showlog = QCheckBox(toggled=self.changed) layout.addWidget(self.showlog) self.rawview = QCheckBox(toggled=self.changed) layout.addWidget(self.rawview) self.hideauto = QCheckBox(toggled=self.changed) layout.addWidget(self.hideauto) app.translateUI(self) def translateUI(self): self.setTitle(_("LilyPond Log")) self.fontLabel.setText(_("Font:")) self.showlog.setText(_("Show log when a job is started")) self.rawview.setText(_("Display plain log output")) self.rawview.setToolTip(_( "If checked, Frescobaldi will not shorten filenames in the log output.""")) self.hideauto.setText(_("Hide automatic engraving jobs")) self.hideauto.setToolTip(_( "If checked, Frescobaldi will not show the log for automatically\n" "started engraving jobs (LilyPond->Auto-engrave).")) def loadSettings(self): s = QSettings() s.beginGroup("log") font = QFont(s.value("fontfamily", "monospace", str)) font.setPointSizeF(s.value("fontsize", 9.0, float)) with qutil.signalsBlocked(self.fontChooser, self.fontSize): self.fontChooser.setCurrentFont(font) self.fontSize.setValue(font.pointSizeF()) self.showlog.setChecked(s.value("show_on_start", True, bool)) self.rawview.setChecked(s.value("rawview", True, bool)) self.hideauto.setChecked(s.value("hide_auto_engrave", False, bool)) def saveSettings(self): s = QSettings() s.beginGroup("log") s.setValue("fontfamily", self.fontChooser.currentFont().family()) s.setValue("fontsize", self.fontSize.value()) s.setValue("show_on_start", self.showlog.isChecked()) s.setValue("rawview", self.rawview.isChecked()) s.setValue("hide_auto_engrave", self.hideauto.isChecked())
class NoteView(QWidget): def __init__(self, parent: QWidget, noteViewManager: NoteViewManager, note: Note): super(QWidget, self).__init__(parent) self.noteViewManager = noteViewManager self.note = note self.notebook = self.noteViewManager.notebook self.setLayout(QVBoxLayout(self)) self.lay = self.layout() self.noteContentEdit = NoteContentEdit(self, self.notebook, note) self.noteContentEdit.anchorClicked.connect(self.onAnchorClicked) self.attachmentsView = NoteAttachmentsView(self, self.notebook, note) self.attachmentsBox = CollapsibleBox(title="Attachments") tmpLay = QVBoxLayout() tmpLay.addWidget(self.attachmentsView) self.attachmentsBox.setContentLayout(tmpLay) self.attachmentsBox.setContentsMargins(0, 0, 0, 0) self.initFormatbar() self.fontBox.setCurrentFont(self.notebook.settings.font()) self.fontSize.setValue(self.notebook.settings.font().pointSize()) self.noteContentEdit.currentCharFormatChanged.connect(self.onCurrentCharFormatChanged) self.lay.addWidget(self.noteContentEdit) self.lay.addWidget(self.attachmentsBox) def initFormatbar(self): self.fontBox = QFontComboBox() self.fontBox.setCurrentFont(self.noteContentEdit.font()) self.fontBox.currentFontChanged.connect(lambda font: self.noteContentEdit.setCurrentFont(font)) # self.families = list(self.fontBox.itemText(i) for i in range(self.fontBox.count())) # # with open("fonts.txt", "w") as f: # for name in self.families: # f.write(name + "\r\n") self.fontSize = QSpinBox() self.fontSize.setValue(self.noteContentEdit.fontPointSize()) self.fontSize.adjustSize() self.fontSize.setSuffix(" pt") self.fontSize.valueChanged.connect(lambda size: self.noteContentEdit.setFontPointSize(size)) fontColor = QAction(QIcon("icons/font-color.png"), "Change font color", self) fontColor.triggered.connect(self.fontColorChanged) boldAction = QAction(QIcon("icons/bold.png"), "Bold", self) boldAction.triggered.connect(self.bold) italicAction = QAction(QIcon("icons/italic.png"), "Italic", self) italicAction.triggered.connect(self.italic) underlAction = QAction(QIcon("icons/underline.png"), "Underline", self) underlAction.triggered.connect(self.underline) strikeAction = QAction(QIcon("icons/strike.png"), "Strike-out", self) strikeAction.triggered.connect(self.strike) superAction = QAction(QIcon("icons/superscript.png"), "Superscript", self) superAction.triggered.connect(self.superScript) subAction = QAction(QIcon("icons/subscript.png"), "Subscript", self) subAction.triggered.connect(self.subScript) alignLeft = QAction(QIcon("icons/align-left.png"), "Align left", self) alignLeft.triggered.connect(self.alignLeft) alignCenter = QAction(QIcon("icons/align-center.png"), "Align center", self) alignCenter.triggered.connect(self.alignCenter) alignRight = QAction(QIcon("icons/align-right.png"), "Align right", self) alignRight.triggered.connect(self.alignRight) alignJustify = QAction(QIcon("icons/align-justify.png"), "Align justify", self) alignJustify.triggered.connect(self.alignJustify) indentAction = QAction(QIcon("icons/indent.png"), "Indent Area", self) indentAction.setShortcut("Ctrl+Tab") indentAction.triggered.connect(self.indent) dedentAction = QAction(QIcon("icons/dedent.png"), "Dedent Area", self) dedentAction.setShortcut("Shift+Tab") dedentAction.triggered.connect(self.dedent) backColor = QAction(QIcon("icons/highlight.png"), "Change background color", self) backColor.triggered.connect(self.highlight) bulletAction = QAction(QIcon("icons/bullet.png"), "Insert bullet List", self) bulletAction.setStatusTip("Insert bullet list") bulletAction.setShortcut("Ctrl+Shift+B") bulletAction.triggered.connect(self.bulletList) numberedAction = QAction(QIcon("icons/number.png"), "Insert numbered List", self) numberedAction.setStatusTip("Insert numbered list") numberedAction.setShortcut("Ctrl+Shift+L") numberedAction.triggered.connect(self.numberList) dateTimeAction = QAction(QIcon("icons/calender.png"), "Insert current date/time", self) dateTimeAction.setStatusTip("Insert current date/time") dateTimeAction.setShortcut("Ctrl+D") dateTimeAction.triggered.connect(self.insertDateTime) wordCountAction = QAction(QIcon("icons/count.png"), "See word/symbol count", self) wordCountAction.setStatusTip("See word/symbol count") wordCountAction.setShortcut("Ctrl+W") wordCountAction.triggered.connect(self.wordCount) tableAction = QAction(QIcon("icons/table.png"), "Insert table", self) tableAction.setStatusTip("Insert table") tableAction.setShortcut("Ctrl+T") tableAction.triggered.connect(self.insertTable) imageAction = QAction(QIcon("icons/image.png"), "Insert image", self) imageAction.setStatusTip("Insert image") imageAction.setShortcut("Ctrl+Shift+I") imageAction.triggered.connect(self.insertImage) linkAction = QAction(QIcon("icons/insert_link.png"), "Insert link", self) linkAction.setStatusTip("Insert link") # linkAction.setShortcut("Ctrl+Shift+L") linkAction.triggered.connect(self.insertLink) linkNoteAction = QAction(QIcon("icons/insert_note_link.png"), "Insert note link", self) linkNoteAction.setStatusTip("Insert note link") # linkAction.setShortcut("Ctrl+Shift+L") linkNoteAction.triggered.connect(self.insertNoteLink) attachAction = QAction(QIcon("icons/attach.png"), "Insert attachment", self) attachAction.setStatusTip("Insert attachment") attachAction.triggered.connect(self.insertAttachment) printAction = QAction(QIcon("icons/print.png"), "Print document", self) printAction.setStatusTip("Print document") printAction.setShortcut("Ctrl+P") printAction.triggered.connect(self.printHandler) previewAction = QAction(QIcon("icons/preview.png"), "Page view", self) previewAction.setStatusTip("Preview page before printing") previewAction.setShortcut("Ctrl+Shift+P") previewAction.triggered.connect(self.preview) viewHistoryAction = QAction(QIcon("icons/history.png"), "Show history", self) viewHistoryAction.setStatusTip("View note content history") viewHistoryAction.setShortcut("Ctrl+H") viewHistoryAction.triggered.connect(self.showHistory) self.formatbar = QToolBar("Format") self.formatbar.setIconSize(QSize(16, 16)) self.lay.addWidget(self.formatbar) self.formatbar.addWidget(self.fontBox) self.formatbar.addWidget(self.fontSize) self.formatbar.addSeparator() self.formatbar.addAction(fontColor) self.formatbar.addAction(backColor) self.formatbar.addSeparator() self.formatbar.addAction(boldAction) self.formatbar.addAction(italicAction) self.formatbar.addAction(underlAction) self.formatbar.addAction(strikeAction) self.formatbar.addAction(superAction) self.formatbar.addAction(subAction) self.formatbar.addSeparator() self.formatbar.addAction(alignLeft) self.formatbar.addAction(alignCenter) self.formatbar.addAction(alignRight) self.formatbar.addAction(alignJustify) self.formatbar.addSeparator() self.formatbar.addAction(indentAction) self.formatbar.addAction(dedentAction) self.formatbar.addSeparator() self.formatbar.addAction(bulletAction) self.formatbar.addAction(numberedAction) self.formatbar.addSeparator() self.formatbar.addAction(wordCountAction) self.formatbar.addAction(tableAction) self.formatbar.addAction(dateTimeAction) self.formatbar.addAction(imageAction) self.formatbar.addSeparator() self.formatbar.addAction(linkAction) self.formatbar.addAction(linkNoteAction) self.formatbar.addAction(attachAction) self.formatbar.addSeparator() self.formatbar.addAction(viewHistoryAction) self.formatbar.addAction(previewAction) self.formatbar.addAction(printAction) def saveChanges(self): self.noteContentEdit.saveChanges() def fontColorChanged(self): # Get a color from the text dialog color = QColorDialog.getColor() # Set it as the new text color self.noteContentEdit.setTextColor(color) def highlight(self): color = QColorDialog.getColor() self.noteContentEdit.setTextBackgroundColor(color) def bold(self): if self.noteContentEdit.fontWeight() == QFont.Bold: self.noteContentEdit.setFontWeight(QFont.Normal) else: self.noteContentEdit.setFontWeight(QFont.Bold) def italic(self): state = self.noteContentEdit.fontItalic() self.noteContentEdit.setFontItalic(not state) def underline(self): state = self.noteContentEdit.fontUnderline() self.noteContentEdit.setFontUnderline(not state) def strike(self): # Grab the text's format fmt = self.noteContentEdit.currentCharFormat() # Set the fontStrikeOut property to its opposite fmt.setFontStrikeOut(not fmt.fontStrikeOut()) # And set the next char format self.noteContentEdit.setCurrentCharFormat(fmt) def superScript(self): # Grab the current format fmt = self.noteContentEdit.currentCharFormat() # And get the vertical alignment property align = fmt.verticalAlignment() # Toggle the state if align == QTextCharFormat.AlignNormal: fmt.setVerticalAlignment(QTextCharFormat.AlignSuperScript) else: fmt.setVerticalAlignment(QTextCharFormat.AlignNormal) # Set the new format self.noteContentEdit.setCurrentCharFormat(fmt) def subScript(self): # Grab the current format fmt = self.noteContentEdit.currentCharFormat() # And get the vertical alignment property align = fmt.verticalAlignment() # Toggle the state if align == QTextCharFormat.AlignNormal: fmt.setVerticalAlignment(QTextCharFormat.AlignSubScript) else: fmt.setVerticalAlignment(QTextCharFormat.AlignNormal) # Set the new format self.noteContentEdit.setCurrentCharFormat(fmt) def alignLeft(self): self.noteContentEdit.setAlignment(Qt.AlignLeft) def alignRight(self): self.noteContentEdit.setAlignment(Qt.AlignRight) def alignCenter(self): self.noteContentEdit.setAlignment(Qt.AlignCenter) def alignJustify(self): self.noteContentEdit.setAlignment(Qt.AlignJustify) def indent(self): # Grab the cursor cursor = self.noteContentEdit.textCursor() if cursor.hasSelection(): # Store the current line/block number temp = cursor.blockNumber() # Move to the selection's end cursor.setPosition(cursor.anchor()) # Calculate range of selection diff = cursor.blockNumber() - temp direction = QTextCursor.Up if diff > 0 else QTextCursor.Down # Iterate over lines (diff absolute value) for n in range(abs(diff) + 1): # Move to start of each line cursor.movePosition(QTextCursor.StartOfLine) # Insert tabbing cursor.insertText("\t") # And move back up cursor.movePosition(direction) # If there is no selection, just insert a tab else: cursor.insertText("\t") def handleDedent(self, cursor): cursor.movePosition(QTextCursor.StartOfLine) # Grab the current line line = cursor.block().text() # If the line starts with a tab character, delete it if line.startswith("\t"): # Delete next character cursor.deleteChar() # Otherwise, delete all spaces until a non-space character is met else: for char in line[:8]: if char != " ": break cursor.deleteChar() def dedent(self): cursor = self.noteContentEdit.textCursor() if cursor.hasSelection(): # Store the current line/block number temp = cursor.blockNumber() # Move to the selection's last line cursor.setPosition(cursor.anchor()) # Calculate range of selection diff = cursor.blockNumber() - temp direction = QTextCursor.Up if diff > 0 else QTextCursor.Down # Iterate over lines for n in range(abs(diff) + 1): self.handleDedent(cursor) # Move up cursor.movePosition(direction) else: self.handleDedent(cursor) def bulletList(self): cursor = self.noteContentEdit.textCursor() # Insert bulleted list cursor.insertList(QTextListFormat.ListDisc) def numberList(self): cursor = self.noteContentEdit.textCursor() # Insert list with numbers cursor.insertList(QTextListFormat.ListDecimal) def insertTable(self): Table(parent=self, text=self.noteContentEdit).show() def insertDateTime(self): # Grab cursor cursor = self.noteContentEdit.textCursor() datetime = strftime(self.noteViewManager.notebook.settings.date_time_insert_format()) # Insert the comboBox's current text cursor.insertText(datetime) def wordCount(self): wc = WordCount(self, self.noteContentEdit) wc.text = self.noteContentEdit wc.getText() wc.show() def insertHyperLynk(self, url: str): cursor = QTextCursor(self.noteContentEdit.document()) format = QTextCharFormat() format.setAnchor(True) format.setAnchorHref(url) cursor.mergeBlockCharFormat(format) def insertLink(self): dialog = LinkAddDialog(self.noteContentEdit) result = dialog.exec_() if result == QDialog.Accepted: cursor = self.noteContentEdit.textCursor() linkAdress = dialog.linkAdress linkCaption = dialog.linkCaption url = QUrl.fromUserInput(linkAdress) linkAdress = url.toString() cursor.insertHtml(f"<a href=\"{linkAdress}\" >{linkCaption}</a>") def insertNoteLink(self): cursor = self.noteContentEdit.textCursor() filename = QFileDialog.getOpenFileName(self.noteContentEdit, 'Open File', ".", "(*.nbf)")[0] if filename: notebook = Notebook.from_file(filename) dialog = NoteSelectDialog(parent=self, notebook=notebook) result = dialog.exec_() if result == QDialog.Accepted: url: QUrl = QUrl.fromLocalFile(filename) url.setScheme("notesmanager") query = QUrlQuery() query.addQueryItem("uuid", str(dialog.selectedNote.uuid)) url.setQuery(query) cursor.insertHtml(f"<a href=\"{url.toString()}\" >{dialog.caption}</a>") # self.text.setReadOnly(True) # self.insertHyperLynk("www.google.com") def preview(self): # Open preview dialog preview = QPrintPreviewDialog() # If a print is requested, open print dialog preview.paintRequested.connect(lambda p: self.noteContentEdit.print_(p)) preview.exec_() def printHandler(self): # Open printing dialog dialog = QPrintDialog() if dialog.exec_() == QDialog.Accepted: self.noteContentEdit.document().print_(dialog.printer()) def showHistory(self): self.noteViewManager.saveChanges() dialog = NoteHistoryView(self, self.note) if dialog.exec_() == QDialog.Accepted: self.note.restore(dialog.restoreIndex) self.noteContentEdit.setHtml(self.note.content) def insertImage(self): # Get image file name # PYQT5 Returns a tuple in PyQt5 filename = \ QFileDialog.getOpenFileName(self.noteContentEdit, 'Insert image', ".", "Images (*.png *.xpm *.jpg *.bmp *.gif)")[ 0] if filename: # Create image object image = QImage(filename) # Error if unloadable if image.isNull(): popup = QMessageBox(QMessageBox.Critical, "Image load error", "Could not load image file!", QMessageBox.Ok, self.noteContentEdit) popup.show() else: # from PIL import Image, ImageDraw import base64 import os content_type = "image/" + os.path.splitext(filename)[1][1:] raw_data = base64.b64encode(open(filename, "rb").read()) uri = ("data:" + content_type + ";" + "base64," + raw_data.decode()) html_code = '<img src="' + uri + '"/>' cursor = self.noteContentEdit.textCursor() cursor.insertHtml(html_code) # random_filename = self.get_random_file_name(os.path.splitext(filename)[1][1:]) # from shutil import copy # copy(filename, dst=random_filename) # cursor.insertImage(image, random_filename) # cursor.insertHtml(html) def onCurrentCharFormatChanged(self, format: QTextCharFormat) -> None: if format.isAnchor(): new_format = QTextCharFormat() new_format.setFont(self.fontBox.currentFont()) new_format.setFontPointSize(self.fontSize.value()) self.noteContentEdit.setCurrentCharFormat(new_format) def onAnchorClicked(self, url: QUrl): from notes.ui.MainWindow import MainWindow import webbrowser host = url.host() scheme = url.scheme() if scheme == "http" or scheme == "https": webbrowser.open(url.toString()) elif scheme == "notesmanager": url.setScheme("file") local_path = url.toLocalFile() query = QUrlQuery(url) uuid = query.queryItemValue("uuid") if local_path == self.notebook.attachment_base.filename: self.noteViewManager.openNote(self.noteViewManager.notebook.get_note_by_uuid(uuid)) else: spawn = MainWindow(None, local_path, uuid) spawn.show() def insertAttachment(self): dialog = QFileDialog() dialog.setFileMode(QFileDialog.ExistingFiles) filenames = dialog.getOpenFileNames(self, 'Insert attachments', ".")[0] self.attachmentsView.addAttachments(filenames)
class GlobalFontDialog(widgets.dialog.Dialog): def __init__(self, parent=None): super(GlobalFontDialog, self).__init__(parent) self._messageLabel.setWordWrap(True) layout = QGridLayout() layout.setContentsMargins(0, 0, 0, 0) self.mainWidget().setLayout(layout) self.romanLabel = QLabel() self.romanCombo = QFontComboBox() self.sansLabel = QLabel() self.sansCombo = QFontComboBox() self.typewriterLabel = QLabel() self.typewriterCombo = QFontComboBox(fontFilters=QFontComboBox.MonospacedFonts) layout.addWidget(self.romanLabel, 0, 0) layout.addWidget(self.romanCombo, 0, 1, 1, 2) layout.addWidget(self.sansLabel, 1, 0) layout.addWidget(self.sansCombo, 1, 1, 1, 2) layout.addWidget(self.typewriterLabel, 2, 0) layout.addWidget(self.typewriterCombo, 2, 1, 1, 2) self.loadSettings() self.finished.connect(self.saveSettings) app.translateUI(self) def translateUI(self): self.setWindowTitle(app.caption(_("Global Fonts"))) self.setMessage(_( "Please select the three global fonts to use for " r"<code>\roman</code>, <code>\sans</code>, and <code>\typewriter</code> " "respectively.")) self.romanLabel.setText(_("Roman Font:")) self.sansLabel.setText(_("Sans Font:")) self.typewriterLabel.setText(_("Typewriter Font:")) def romanFont(self): return self.romanCombo.currentFont().family() def setromanFont(self, family): self.romanCombo.setCurrentFont(QFont(family)) def sansFont(self): return self.sansCombo.currentFont().family() def setSansFont(self, family): self.sansCombo.setCurrentFont(QFont(family)) def typewriterFont(self): return self.typewriterCombo.currentFont().family() def settypewriterFont(self, family): self.typewriterCombo.setCurrentFont(QFont(family)) def loadSettings(self): s = QSettings() s.beginGroup("global_font_dialog") roman = s.value("roman", "Century Schoolbook L", str) self.romanCombo.setCurrentFont(QFont(roman)) sans = s.value("sans", "sans-serif", str) self.sansCombo.setCurrentFont(QFont(sans)) typewriter = s.value("typewriter", "monospace", str) self.typewriterCombo.setCurrentFont(QFont(typewriter)) def saveSettings(self): s = QSettings() s.beginGroup("global_font_dialog") s.setValue("roman", self.romanCombo.currentFont().family()) s.setValue("sans", self.sansCombo.currentFont().family()) s.setValue("typewriter", self.typewriterCombo.currentFont().family())
def create_ui(self): # 1.文字标签 # QLabel(显示的文字, 父标签/放到哪个窗口上) label1 = QLabel('用户名:', self) # 一般不常用的移动坐标 label1.move(50, 10) # 2.按钮 btn1 = QPushButton('登录', self) btn1.move(50, 50) # css语法:选择器{属性1:属性值1; 属性2:属性值2;..} # color - 字体颜色,对应的值:颜色单词, rbg(255, 0, 0) # btn1.setStyleSheet('QPushButton{}') btn2 = QRadioButton('男', self) btn2.move(50, 100) btn3 = QCheckBox('篮球', self) btn3.move(50, 150) btn4 = QCommandLinkButton('hello', 'hellowword', self) btn4.move(50, 200) b1 = QDialogButtonBox.StandardButton.Ok b2 = QDialogButtonBox.StandardButton.Cancel btn5 = QDialogButtonBox(b2, self) btn5.move(50, 300) # 3.输入框 input1 = QLineEdit(self) input1.move(150, 10) input2 = QLineEdit('admin', self) input2.move(150, 50) input1.setText('张三') # 富文本 input3 = QTextEdit('张三', self) input3.move(50, 300) # 设置成只读 input3.setReadOnly(True) # 只能显示纯文本 input4 = QPlainTextEdit(self) input4.move(300, 10) # 输入数值 input5 = QSpinBox(self) input5.move(100, 100) input5.setMinimum(10) input5.setMaximum(20) input5.setValue(15) print(input5.value()) # 获取当前值 # 输入小数 input6 = QDoubleSpinBox(self) input6.move(100, 150) # 下拉菜单 input7 = QComboBox(self) input7.addItems(['item1', 'item2']) input7.move(150, 200) print(input7.currentText()) # 获取当前选中的选项,适用input8 input8 = QFontComboBox(self) input8.move(350, 300) input8.setCurrentIndex(2) print(input8.currentText()) label1.setFont(input8.currentFont()) # 日期选择 input9 = QDateEdit(date.today(), self) input9.move(300, 400) # 选择颜色 input10 = QColorDialog(self) input10.move(400, 400) # input10.show() input11 = QDial(self) input11.move(300, 200) input12 = QSlider(self) input12.move(430, 350) input12.setMaximum(100) input12.setMinimum(-100) input12.setValue(20) input12.setOrientation(Qt.Horizontal) # 设置为水平方向
class LogTool(preferences.Group): def __init__(self, page): super(LogTool, self).__init__(page) layout = QVBoxLayout() self.setLayout(layout) self.fontLabel = QLabel() self.fontChooser = QFontComboBox(currentFontChanged=self.changed) self.fontSize = QDoubleSpinBox(valueChanged=self.changed) self.fontSize.setRange(6.0, 32.0) self.fontSize.setSingleStep(0.5) self.fontSize.setDecimals(1) box = QHBoxLayout() box.addWidget(self.fontLabel) box.addWidget(self.fontChooser, 1) box.addWidget(self.fontSize) layout.addLayout(box) self.showlog = QCheckBox(toggled=self.changed) layout.addWidget(self.showlog) self.rawview = QCheckBox(toggled=self.changed) layout.addWidget(self.rawview) self.hideauto = QCheckBox(toggled=self.changed) layout.addWidget(self.hideauto) app.translateUI(self) def translateUI(self): self.setTitle(_("LilyPond Log")) self.fontLabel.setText(_("Font:")) self.showlog.setText(_("Show log when a job is started")) self.rawview.setText(_("Display plain log output")) self.rawview.setToolTip( _("If checked, Frescobaldi will not shorten filenames in the log output." "")) self.hideauto.setText(_("Hide automatic engraving jobs")) self.hideauto.setToolTip( _("If checked, Frescobaldi will not show the log for automatically\n" "started engraving jobs (LilyPond->Auto-engrave).")) def loadSettings(self): s = QSettings() s.beginGroup("log") font = QFont(s.value("fontfamily", "monospace", str)) font.setPointSizeF(s.value("fontsize", 9.0, float)) with qutil.signalsBlocked(self.fontChooser, self.fontSize): self.fontChooser.setCurrentFont(font) self.fontSize.setValue(font.pointSizeF()) self.showlog.setChecked(s.value("show_on_start", True, bool)) self.rawview.setChecked(s.value("rawview", True, bool)) self.hideauto.setChecked(s.value("hide_auto_engrave", False, bool)) def saveSettings(self): s = QSettings() s.beginGroup("log") s.setValue("fontfamily", self.fontChooser.currentFont().family()) s.setValue("fontsize", self.fontSize.value()) s.setValue("show_on_start", self.showlog.isChecked()) s.setValue("rawview", self.rawview.isChecked()) s.setValue("hide_auto_engrave", self.hideauto.isChecked())
class Form(QWidget): def __init__(self): super().__init__() self.GetItems() self.say_altciz = 0 self.say_italic = 0 self.say_bold = 0 self.SetScreen() def SetScreen(self): self.setWindowTitle("Işılgan Metin Editör") self.resize(700, 500) sshFile = "style.css" with open(sshFile, "r") as fh: self.setStyleSheet(fh.read()) self.spiner.setValue(15) self.richText.setFontPointSize(self.spiner.value()) def GetItems(self): layout = QGridLayout() #rich self.richText = QTextEdit() self.richText.textChanged.connect(self.richText_changed) self.richText.setStyleSheet("background-color:#7E7474") #rich #save save = QPushButton() save.setIcon(QIcon("iconlar/save.png")) save.clicked.connect(self.save_clicked) save.setFixedSize(80, 20) #save #opentext opentext = QPushButton() opentext.setIcon(QIcon("iconlar/open.png")) opentext.clicked.connect(self.opentext_clicked) opentext.setFixedSize(80, 20) #opentext #fontSet self.fontCombo = QFontComboBox() self.fontCombo.activated.connect(self.fontSelect) self.fontCombo.setFixedSize(150, 20) #fontSet #fontSize self.spiner = QSpinBox() self.spiner.valueChanged.connect(self.sizeSelect) self.spiner.setFixedSize(130, 20) #fontSize #colorSelect self.colorButton = QPushButton() self.colorButton.setIcon(QIcon("iconlar/color.png")) self.colorButton.clicked.connect(self.colorButton_clicked) self.colorButton.setFixedSize(50, 20) #colorSelect #Addimage self.addImage = QPushButton() self.addImage.clicked.connect(self.addImage_clicked) self.addImage.setIcon(QIcon("iconlar/add.png")) self.addImage.setFixedSize(30, 20) #Addimage #FindWord self.findWord = QPushButton() self.findWord.setIcon(QIcon("iconlar/find.png")) self.findWord.clicked.connect(self.findWord_clicked) self.findWord.setFixedSize(30, 20) #FindWord #hizalamaveBoldİtalicMenuOpen self.widg1 = QWidget() self.widg2 = QWidget() self.toolBox = QToolBox() self.toolBox.setFixedSize(150, 300) self.ortala = QPushButton() self.ortala.setFixedSize(30, 40) self.ortala.setIcon(QIcon("iconlar/center")) self.ortala.clicked.connect(self.yaziyi_ortala) self.sağyasla = QPushButton() self.sağyasla.setIcon(QIcon("iconlar/right.png")) self.sağyasla.setFixedSize(30, 40) self.sağyasla.clicked.connect(self.yaziyi_sagayasla) self.solaYasla = QPushButton() self.solaYasla.setIcon(QIcon("iconlar/left.png")) self.solaYasla.setFixedSize(30, 40) self.solaYasla.clicked.connect(self.yaziyi_solayasla) self.ikiyanayasla = QPushButton() self.ikiyanayasla.setIcon(QIcon("iconlar/justify_align.png")) self.ikiyanayasla.setFixedSize(30, 40) self.ikiyanayasla.clicked.connect(self.yaziyi_ikiyanayasla) self.bold = QPushButton() self.bold.setFixedSize(30, 40) self.bold.setIcon(QIcon("iconlar/Bold.png")) self.bold.clicked.connect(self.bold_yap) self.italic = QPushButton() self.italic.setIcon(QIcon("iconlar/italic.png")) self.italic.setFixedSize(30, 40) self.italic.clicked.connect(self.italic_yap) self.altıçizili = QPushButton() self.altıçizili.setIcon(QIcon("iconlar/underline.png")) self.altıçizili.setFixedSize(30, 40) self.altıçizili.clicked.connect(self.altiniciz) self.layoutHizalama = QGridLayout() self.layoutHizalama.addWidget(self.ortala, 0, 0) self.layoutHizalama.addWidget(self.sağyasla, 1, 0) self.layoutHizalama.addWidget(self.solaYasla, 2, 0) self.layoutHizalama.addWidget(self.ikiyanayasla, 3, 0) self.layoutBoldİtalic = QGridLayout() self.layoutBoldİtalic.addWidget(self.bold, 0, 0) self.layoutBoldİtalic.addWidget(self.italic, 1, 0) self.layoutBoldİtalic.addWidget(self.altıçizili, 2, 0) self.widg1.setLayout(self.layoutHizalama) self.widg2.setLayout(self.layoutBoldİtalic) self.toolBox.addItem(self.widg1, "hizalamalar") self.toolBox.addItem(self.widg2, "Yazı biçimleri") #hizalamaBoldİtalicMenuOpen layout.addWidget(save, 5, 1) layout.addWidget(self.richText, 0, 0, -1, 1) layout.addWidget(opentext, 6, 1) layout.addWidget(self.spiner, 4, 1) layout.addWidget(self.fontCombo, 3, 1) layout.addWidget(self.colorButton, 7, 1) layout.addWidget(self.addImage, 8, 1) layout.addWidget(self.findWord, 9, 1) layout.addWidget(self.toolBox, 10, 1) self.setLayout(layout) def yaziyi_ortala(self): self.richText.setAlignment(Qt.AlignCenter) def yaziyi_sagayasla(self): self.richText.setAlignment(Qt.AlignRight) def yaziyi_solayasla(self): self.richText.setAlignment(Qt.AlignLeft) def yaziyi_ikiyanayasla(self): self.richText.setAlignment(Qt.AlignJustify) def bold_yap(self): if (self.say_bold % 2 == 0): self.richText.setFontWeight(QFont.Bold) else: self.richText.setFontWeight(QFont.Normal) self.say_bold = self.say_bold + 1 def italic_yap(self): if (self.say_italic % 2 == 0): self.richText.setFontItalic(True) else: self.richText.setFontItalic(False) self.say_italic = self.say_italic + 1 def altiniciz(self): if (self.say_altciz % 2 == 0): self.richText.setFontUnderline(True) else: self.richText.setFontUnderline(False) self.say_altciz = self.say_altciz + 1 def richText_changed(self): text = self.richText.toPlainText() temp = 0 for i in text.split(" "): temp = temp + 1 self.setWindowTitle("kelime sayısı:" + str(temp)) #burası henüz tam doğru çalışmıyor def findWord_clicked(self): aranan, onay = QInputDialog.getText(self, " aranan kelimeyi giriniz:", "kelime bul") if not aranan: return col = QColorDialog.getColor(self.richText.textColor(), self) if not col.isValid(): return fmt = QTextCharFormat() fmt.setForeground(col) print("\nfmt.setForeground(col)", col) fmt.setFontPointSize(14) self.richText.moveCursor(QTextCursor.Start) self.countWords = 0 # Find whole words while self.richText.find(aranan, QTextDocument.FindWholeWords): self.mergeFormatOnWordOrSelection(fmt) self.countWords += 1 QMessageBox.information( self, "Information", "word->`{text}` {countWords}` adet bulundu".format( text=aranan, countWords=self.countWords)) def mergeFormatOnWordOrSelection(self, format): cursor = self.richText.textCursor() if not cursor.hasSelection(): cursor.select(QTextCursor.WordUnderCursor) cursor.mergeCharFormat(format) self.richText.mergeCurrentCharFormat(format) def addImage_clicked(self): imagePath = QFileDialog.getOpenFileName(self, 'Open file') document = self.richText.document() cursor = QTextCursor(document) cursor.insertImage(imagePath[0]) #getopenfilename tupple döndürdüğü için ve 0.indexde path olduğu için 0.indexi verdik def colorButton_clicked(self): color = QColorDialog.getColor() self.richText.setTextColor(color) def sizeSelect(self): self.richText.setFontPointSize(self.spiner.value()) def fontSelect(self): self.richText.setFont(self.fontCombo.currentFont()) def opentext_clicked(self): try: filename = QFileDialog.getOpenFileName(self, 'Open File') if filename[0]: f = open(filename[0], 'r') with f: data = f.read() self.richText.setText(data) except: QMessageBox.about( self, "Onu nasıl açayım be güzel kardeşim", "Kötü şeyler oldu olur arada öyle şeyler takma eğer sorun devam ederse bildir" ) def save_clicked(self): try: fname = QFileDialog.getExistingDirectory(self, 'Open f', '/home') metin, onay = QInputDialog.getText(self, " dosyanın adını giriniz", "dosya adı:") metinuzantı, onay = QInputDialog.getText( self, " dosyanın uzantısını giriniz", "dosya uzantısı:") metinad = "" uzantıad = "" if onay == True: metinad = metin uzantıad = metinuzantı with open(fname + "/" + metinad + "." + uzantıad, 'w') as f: my_text = self.richText.toPlainText() f.write(my_text) QMessageBox.about(self, "Bilgilendirme", "Başarı ile kaydedildi") except: QMessageBox.about(self, "Runtime ERROR", "Birşey oldu")
class TextItemDlg(QDialog): def __init__(self, item=None, position=None, scene=None, parent=None): super(QDialog, self).__init__(parent) self.parentForm = parent self.item = item self.position = position self.scene = scene self.editor = QTextEdit() self.editor.setAcceptRichText(True) self.editor.setTabChangesFocus(True) editorLabel = QLabel("&Text:") editorLabel.setBuddy(self.editor) self.fontComboBox = QFontComboBox() self.fontComboBox.setCurrentFont(QFont("Times", PointSize)) fontLabel = QLabel("&Font:") fontLabel.setBuddy(self.fontComboBox) self.fontSpinBox = QSpinBox() self.fontSpinBox.setAlignment(Qt.AlignRight | Qt.AlignVCenter) self.fontSpinBox.setRange(6, 280) self.fontSpinBox.setValue(PointSize) fontSizeLabel = QLabel("&Size:") fontSizeLabel.setBuddy(self.fontSpinBox) self.textBoxName = QLineEdit() BoxNameLabel = QLabel("&BoxName:") BoxNameLabel.setBuddy(self.textBoxName) self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False) if self.item is not None: self.editor.setPlainText(self.item.toPlainText()) self.fontComboBox.setCurrentFont(self.item.font()) self.fontSpinBox.setValue(self.item.font().pointSize()) self.textBoxName.setText(self.item.boxName) layout = QGridLayout() layout.addWidget(editorLabel, 0, 0) layout.addWidget(self.editor, 1, 0, 1, 6) layout.addWidget(fontLabel, 2, 0) layout.addWidget(self.fontComboBox, 2, 1, 1, 2) layout.addWidget(fontSizeLabel, 2, 3) layout.addWidget(self.fontSpinBox, 2, 4, 1, 2) layout.addWidget( self.buttonBox, 4, 0, ) layout.addWidget( self.textBoxName, 3, 1, ) layout.addWidget(BoxNameLabel, 3, 0) fontSizeLabel.hide() self.fontComboBox.hide() fontLabel.hide() self.fontSpinBox.hide() self.setLayout(layout) self.fontComboBox.currentFontChanged.connect(self.updateUi) self.fontSpinBox.valueChanged.connect(self.updateUi) self.editor.textChanged.connect(self.updateUi) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.setWindowTitle("Page Designer - {0} CodeBox Item".format( "Add" if self.item is None else "Edit")) self.updateUi() def updateUi(self): font = self.fontComboBox.currentFont() font.setPointSize(self.fontSpinBox.value()) self.editor.document().setDefaultFont(font) self.buttonBox.button(QDialogButtonBox.Ok).setEnabled( bool(self.editor.toPlainText())) def accept(self): if self.item is None: self.item = TextItem("", "", self.position, self.scene, self.parentForm) font = self.fontComboBox.currentFont() font.setPointSize(self.fontSpinBox.value()) self.item.setFont(font) self.item.setPlainText(self.editor.toPlainText()) self.item.boxName = self.textBoxName.text() self.item.update() self.parentForm.dicText[self.item.boxName] = self.item global Dirty Dirty = True QDialog.accept(self)
class Browser(preferences.Group): def __init__(self, page): super(Browser, self).__init__(page) layout = QGridLayout() self.setLayout(layout) self.languagesLabel = QLabel() self.languages = QComboBox(currentIndexChanged=self.changed) layout.addWidget(self.languagesLabel, 0, 0) layout.addWidget(self.languages, 0, 1) items = ['', ''] items.extend(language_names.languageName(l, l) for l in lilydoc.translations) self.languages.addItems(items) self.fontLabel = QLabel() self.fontChooser = QFontComboBox(currentFontChanged=self.changed) self.fontSize = QSpinBox(valueChanged=self.changed) self.fontSize.setRange(6, 32) self.fontSize.setSingleStep(1) layout.addWidget(self.fontLabel, 1, 0) layout.addWidget(self.fontChooser, 1, 1) layout.addWidget(self.fontSize, 1, 2) app.translateUI(self) def translateUI(self): self.setTitle(_("Documentation Browser")) self.languagesLabel.setText(_("Preferred Language:")) self.languages.setItemText(0, _("Default")) self.languages.setItemText(1, _("English (untranslated)")) self.fontLabel.setText(_("Font:")) def loadSettings(self): s = QSettings() s.beginGroup("documentation") lang = s.value("language", "default", str) if lang in lilydoc.translations: i = lilydoc.translations.index(lang) + 2 elif lang == "C": i = 1 else: i = 0 self.languages.setCurrentIndex(i) font = self.font() family = s.value("fontfamily", "", str) if family: font.setFamily(family) size = s.value("fontsize", 16, int) with qutil.signalsBlocked(self.fontChooser, self.fontSize): self.fontChooser.setCurrentFont(font) self.fontSize.setValue(size) def saveSettings(self): s = QSettings() s.beginGroup("documentation") langs = ['default', 'C'] + lilydoc.translations s.setValue("language", langs[self.languages.currentIndex()]) s.setValue("fontfamily", self.fontChooser.currentFont().family()) s.setValue("fontsize", self.fontSize.value())
class SettingsEditDialog(QDialog): def __init__(self, parent=None): super().__init__(parent) self.setModal(True) self.setWindowTitle('Settings') self.setMinimumWidth(400) self.accepted.connect(self.save) # Editor group self.font_family_input = QFontComboBox() self.font_size_input = QSpinBox() self.font_size_input.setRange(8, 24) self.font_size_input.setSuffix(' pt') self.tab_size_input = QSpinBox() self.tab_size_input.setRange(1, 16) self.tab_size_input.setSuffix(' spaces') self.enable_text_wrapping_input = QCheckBox('Enable text wrapping') editor_layout = QFormLayout() editor_layout.addRow('Font family:', self.font_family_input) editor_layout.addRow('Font size:', self.font_size_input) editor_layout.addRow('Tab size:', self.tab_size_input) editor_layout.addRow('', self.enable_text_wrapping_input) editor_group = QGroupBox('Editor') editor_group.setLayout(editor_layout) # Buttons edit_project_button = QPushButton('Edit default project...') edit_project_button.clicked.connect( lambda: projects.show_edit_dialog('default')) save_button = QPushButton('OK') save_button.setDefault(True) save_button.clicked.connect(self.accept) cancel_button = QPushButton('Cancel') cancel_button.clicked.connect(self.reject) button_layout = QHBoxLayout() button_layout.addWidget(edit_project_button, 1, Qt.AlignLeft) button_layout.addWidget(save_button, 0, Qt.AlignRight) button_layout.addWidget(cancel_button) # Main layout main_layout = QVBoxLayout() main_layout.addWidget(editor_group) main_layout.addLayout(button_layout) self.setLayout(main_layout) def show(self): font = QFont(value('editor/font_family')) self.font_family_input.setCurrentFont(font) self.font_family_input.setCurrentText(QFontInfo(font).family()) self.font_family_input.setFocus(Qt.OtherFocusReason) self.font_size_input.setValue(value('editor/font_size')) self.tab_size_input.setValue(value('editor/tab_size')) self.enable_text_wrapping_input.setChecked( value('editor/enable_text_wrapping')) super().show() def save(self): set_value('editor/font_family', QFontInfo(self.font_family_input.currentFont()).family()) set_value('editor/font_size', self.font_size_input.value()) set_value('editor/tab_size', self.tab_size_input.value()) set_value('editor/enable_text_wrapping', self.enable_text_wrapping_input.isChecked()) edit_dialog_saved().emit()
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() centralWidget = QWidget() fontLabel = QLabel("Font:") self.fontCombo = QFontComboBox() sizeLabel = QLabel("Size:") self.sizeCombo = QComboBox() styleLabel = QLabel("Style:") self.styleCombo = QComboBox() fontMergingLabel = QLabel("Automatic Font Merging:") self.fontMerging = QCheckBox() self.fontMerging.setChecked(True) self.scrollArea = QScrollArea() self.characterWidget = CharacterWidget() self.scrollArea.setWidget(self.characterWidget) self.findStyles(self.fontCombo.currentFont()) self.findSizes(self.fontCombo.currentFont()) self.lineEdit = QLineEdit() clipboardButton = QPushButton("&To clipboard") self.clipboard = QApplication.clipboard() self.fontCombo.currentFontChanged.connect(self.findStyles) self.fontCombo.activated[str].connect(self.characterWidget.updateFont) self.styleCombo.activated[str].connect(self.characterWidget.updateStyle) self.sizeCombo.currentIndexChanged[str].connect(self.characterWidget.updateSize) self.characterWidget.characterSelected.connect(self.insertCharacter) clipboardButton.clicked.connect(self.updateClipboard) controlsLayout = QHBoxLayout() controlsLayout.addWidget(fontLabel) controlsLayout.addWidget(self.fontCombo, 1) controlsLayout.addWidget(sizeLabel) controlsLayout.addWidget(self.sizeCombo, 1) controlsLayout.addWidget(styleLabel) controlsLayout.addWidget(self.styleCombo, 1) controlsLayout.addWidget(fontMergingLabel) controlsLayout.addWidget(self.fontMerging, 1) controlsLayout.addStretch(1) lineLayout = QHBoxLayout() lineLayout.addWidget(self.lineEdit, 1) lineLayout.addSpacing(12) lineLayout.addWidget(clipboardButton) centralLayout = QVBoxLayout() centralLayout.addLayout(controlsLayout) centralLayout.addWidget(self.scrollArea, 1) centralLayout.addSpacing(4) centralLayout.addLayout(lineLayout) centralWidget.setLayout(centralLayout) self.setCentralWidget(centralWidget) self.setWindowTitle("Character Map") def findStyles(self, font): fontDatabase = QFontDatabase() currentItem = self.styleCombo.currentText() self.styleCombo.clear() for style in fontDatabase.styles(font.family()): self.styleCombo.addItem(style) styleIndex = self.styleCombo.findText(currentItem) if styleIndex == -1: self.styleCombo.setCurrentIndex(0) else: self.styleCombo.setCurrentIndex(styleIndex) def findSizes(self, font): fontDatabase = QFontDatabase() currentSize = self.sizeCombo.currentText() self.sizeCombo.blockSignals(True) self.sizeCombo.clear() if fontDatabase.isSmoothlyScalable(font.family(), fontDatabase.styleString(font)): for size in QFontDatabase.standardSizes(): self.sizeCombo.addItem(str(size)) self.sizeCombo.setEditable(True) else: for size in fontDatabase.smoothSizes(font.family(), fontDatabase.styleString(font)): self.sizeCombo.addItem(str(size)) self.sizeCombo.setEditable(False) self.sizeCombo.blockSignals(False) sizeIndex = self.sizeCombo.findText(currentSize) if sizeIndex == -1: self.sizeCombo.setCurrentIndex(max(0, self.sizeCombo.count() / 3)) else: self.sizeCombo.setCurrentIndex(sizeIndex) def insertCharacter(self, character): self.lineEdit.insert(character) def updateClipboard(self): self.clipboard.setText(self.lineEdit.text(), QClipboard.Clipboard) self.clipboard.setText(self.lineEdit.text(), QClipboard.Selection)
class Preferences(QDialog): # Signal to warn that the window is closed settingsClosed = pyqtSignal() def __init__(self, parent=None): super(Preferences, self).__init__(parent) # Main container # This contains a grid main_box = QVBoxLayout(self) main_box.setContentsMargins(200, 50, 200, 100) # The grid contains two containers # left container and right container grid = QGridLayout() # Left Container left_container = QVBoxLayout() left_container.setContentsMargins(0, 0, 0, 0) # General group_gral = QGroupBox(self.tr("General")) box_gral = QVBoxLayout(group_gral) # Updates btn_updates = QPushButton(self.tr("Check for updates")) box_gral.addWidget(btn_updates) # Language group_language = QGroupBox(self.tr("Language")) box = QVBoxLayout(group_language) # Find .qm files in language path available_langs = file_manager.get_files_from_folder( settings.LANGUAGE_PATH) languages = ["English"] + available_langs self._combo_lang = QComboBox() box.addWidget(self._combo_lang) self._combo_lang.addItems(languages) self._combo_lang.currentIndexChanged[int].connect( self._change_lang) if PSetting.LANGUAGE: self._combo_lang.setCurrentText(PSetting.LANGUAGE) box.addWidget(QLabel(self.tr("(Requires restart)"))) # Add widgets left_container.addWidget(group_gral) left_container.addWidget(group_language) left_container.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding)) # Right Container right_container = QVBoxLayout() right_container.setContentsMargins(0, 0, 0, 0) # Editor editor_group = QGroupBox(self.tr("Editor Configurations")) box_editor = QHBoxLayout(editor_group) # Current line self._highlight_current_line = QCheckBox( self.tr("Highlight Current Line")) self._highlight_current_line.setChecked( PSetting.HIGHLIGHT_CURRENT_LINE) self._highlight_current_line.stateChanged[int].connect( self.__current_line_value_changed) box_editor.addWidget(self._highlight_current_line) # Matching paren self._matching_paren = QCheckBox(self.tr("Matching Parenthesis")) self._matching_paren.setChecked( PSetting.MATCHING_PARENTHESIS) self._matching_paren.stateChanged[int].connect( self.__set_enabled_matching_parenthesis) box_editor.addWidget(self._matching_paren) # Font group font_group = QGroupBox(self.tr("Font")) font_grid = QGridLayout(font_group) font_grid.addWidget(QLabel(self.tr("Family")), 0, 0) self._combo_font = QFontComboBox() self._combo_font.setCurrentFont(PSetting.FONT) font_grid.addWidget(self._combo_font, 0, 1) font_grid.addWidget(QLabel(self.tr("Point Size")), 1, 0) self._combo_font_size = QComboBox() fdb = QFontDatabase() combo_sizes = fdb.pointSizes(PSetting.FONT.family()) current_size_index = combo_sizes.index( PSetting.FONT.pointSize()) self._combo_font_size.addItems([str(f) for f in combo_sizes]) self._combo_font_size.setCurrentIndex(current_size_index) font_grid.addWidget(self._combo_font_size, 1, 1) right_container.addWidget(editor_group) right_container.addWidget(font_group) right_container.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding)) # Add widgets grid.addLayout(left_container, 0, 0) grid.addLayout(right_container, 0, 1) main_box.addLayout(grid) # Button close and reset hbox = QHBoxLayout() hbox.setSpacing(20) hbox.addItem(QSpacerItem(1, 0, QSizePolicy.Expanding)) btn_cancel = QPushButton(self.tr("Back")) hbox.addWidget(btn_cancel) btn_reset = QPushButton(self.tr("Reset Configurations")) hbox.addWidget(btn_reset) main_box.addLayout(hbox) # Overlay self.overlay = overlay_widget.OverlayWidget(self) self.overlay.hide() # Effect and animations self.effect = QGraphicsOpacityEffect() self.setGraphicsEffect(self.effect) duration, x = 180, 150 # Animation duration # Animation start # Opacity animation self.opacity_animation_s = QPropertyAnimation(self.effect, b"opacity") self.opacity_animation_s.setDuration(duration) self.opacity_animation_s.setStartValue(0.0) self.opacity_animation_s.setEndValue(1.0) # X animation self.x_animation_s = QPropertyAnimation(self, b"geometry") self.x_animation_s.setDuration(duration) self.x_animation_s.setStartValue(QRect(x, 0, parent.width(), parent.height())) self.x_animation_s.setEndValue(QRect(0, 0, parent.width(), parent.height())) # Animation end # Opacity animation self.opacity_animation_e = QPropertyAnimation(self.effect, b"opacity") self.opacity_animation_e.setDuration(duration) self.opacity_animation_e.setStartValue(1.0) self.opacity_animation_e.setEndValue(0.0) # X animation self.x_animation_e = QPropertyAnimation(self, b"geometry") self.x_animation_e.setDuration(duration) self.x_animation_e.setStartValue(QRect(0, 0, parent.width(), parent.height())) self.x_animation_e.setEndValue(QRect(-x, 0, parent.width(), parent.height())) # Group animation start self.group_animation_s = QParallelAnimationGroup() self.group_animation_s.addAnimation(self.opacity_animation_s) self.group_animation_s.addAnimation(self.x_animation_s) # Group animation end self.group_animation_e = QParallelAnimationGroup() self.group_animation_e.addAnimation(self.opacity_animation_e) self.group_animation_e.addAnimation(self.x_animation_e) # Connections self.group_animation_e.finished.connect( self._on_group_animation_finished) btn_cancel.clicked.connect(self.close) btn_reset.clicked.connect(self._reset_settings) btn_updates.clicked.connect(self._check_for_updates) # self.thread.finished.connect(self._on_thread_finished) self._combo_font.currentFontChanged.connect( self._change_font) self._combo_font_size.currentTextChanged.connect( self._change_font_size) def __current_line_value_changed(self, value): qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat) qs.setValue('highlight_current_line', value) PSetting.HIGHLIGHT_CURRENT_LINE = value def __set_enabled_matching_parenthesis(self, value): qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat) qs.setValue("matching_parenthesis", value) PSetting.MATCHING_PARENTHESIS = value def _change_font(self, font): # FIXME: un quilombo esto central = Pireal.get_service("central") mcontainer = central.get_active_db() if mcontainer is not None: query_widget = mcontainer.query_container.currentWidget() if query_widget is not None: weditor = query_widget.get_editor() if weditor is not None: qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat) weditor.set_font(font) qs.setValue("font", font) def _change_font_size(self, size): # FIXME: un quilombo esto font = self._combo_font.currentFont() font.setPointSize(int(size)) central = Pireal.get_service("central") mcontainer = central.get_active_db() if mcontainer is not None: query_widget = mcontainer.query_container.currentWidget() if query_widget is not None: weditor = query_widget.get_editor() if weditor is not None: qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat) weditor.set_font(font) qs.setValue("font", font) def showEvent(self, event): super(Preferences, self).showEvent(event) self.group_animation_s.start() def resizeEvent(self, event): self.overlay.resize(self.size()) event.accept() def done(self, result): self.res = result self.group_animation_e.start() def _on_group_animation_finished(self): super(Preferences, self).done(self.res) self.settingsClosed.emit() def _check_for_updates(self): # Thread self._thread = QThread() self._updater = updater.Updater() self._updater.moveToThread(self._thread) self._thread.started.connect(self._updater.check_updates) self._updater.finished.connect(self.__on_thread_update_finished) # Show overlay widget self.overlay.show() # Start thread self._thread.start() def __on_thread_update_finished(self): # Hide overlay widget self.overlay.hide() self._thread.quit() msg = QMessageBox(self) if not self._updater.error: if self._updater.version: version = self._updater.version msg.setWindowTitle(self.tr("New version available!")) msg.setText(self.tr("Check the web site to " "download <b>Pireal {}</b>".format( version))) download_btn = msg.addButton(self.tr("Download!"), QMessageBox.YesRole) msg.addButton(self.tr("Cancel"), QMessageBox.RejectRole) msg.exec_() r = msg.clickedButton() if r == download_btn: webbrowser.open_new( "http://centaurialpha.github.io/pireal") else: msg.setWindowTitle(self.tr("Information")) msg.setText(self.tr("Last version installed")) msg.addButton(self.tr("Ok"), QMessageBox.AcceptRole) msg.exec_() else: msg.critical(self, self.tr("Error"), self.tr("Connection error")) self._thread.deleteLater() self._updater.deleteLater() def _reset_settings(self): """ Remove all settings """ msg = QMessageBox(self) msg.setWindowTitle(self.tr("Reset Settings")) msg.setText(self.tr("Are you sure you want to clear all settings?")) msg.setIcon(QMessageBox.Question) msg.addButton(self.tr("No"), QMessageBox.NoRole) yes_btn = msg.addButton(self.tr("Yes"), QMessageBox.YesRole) msg.exec_() r = msg.clickedButton() if r == yes_btn: QSettings(settings.SETTINGS_PATH, QSettings.IniFormat).clear() self.close() def _change_lang(self, index): lang = self._combo_lang.itemText(index) qs = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat) qs.setValue('language', lang)
class FontsColors(preferences.Page): def __init__(self, dialog): super(FontsColors, self).__init__(dialog) layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) self.scheme = SchemeSelector(self) layout.addWidget(self.scheme) self.printScheme = QCheckBox() layout.addWidget(self.printScheme) hbox = QHBoxLayout() self.tree = QTreeWidget(self) self.tree.setHeaderHidden(True) self.tree.setAnimated(True) self.stack = QStackedWidget(self) hbox.addWidget(self.tree) hbox.addWidget(self.stack) layout.addLayout(hbox) hbox = QHBoxLayout() self.fontLabel = QLabel() self.fontChooser = QFontComboBox() self.fontSize = QDoubleSpinBox() self.fontSize.setRange(6.0, 32.0) self.fontSize.setSingleStep(0.5) self.fontSize.setDecimals(1) hbox.addWidget(self.fontLabel) hbox.addWidget(self.fontChooser, 1) hbox.addWidget(self.fontSize) layout.addLayout(hbox) # add the items to our list self.baseColorsItem = i = QTreeWidgetItem() self.tree.addTopLevelItem(i) self.defaultStylesItem = i = QTreeWidgetItem() self.tree.addTopLevelItem(i) self.defaultStyles = {} for name in textformats.defaultStyles: self.defaultStyles[name] = i = QTreeWidgetItem() self.defaultStylesItem.addChild(i) i.name = name self.defaultStylesItem.setExpanded(True) self.allStyles = {} for group, styles in ly.colorize.default_mapping(): i = QTreeWidgetItem() children = {} self.allStyles[group] = (i, children) self.tree.addTopLevelItem(i) i.group = group for name, base, clss in styles: j = QTreeWidgetItem() j.name = name j.base = base i.addChild(j) children[name] = j self.baseColorsWidget = BaseColors(self) self.customAttributesWidget = CustomAttributes(self) self.emptyWidget = QWidget(self) self.stack.addWidget(self.baseColorsWidget) self.stack.addWidget(self.customAttributesWidget) self.stack.addWidget(self.emptyWidget) self.tree.currentItemChanged.connect(self.currentItemChanged) self.tree.setCurrentItem(self.baseColorsItem) self.scheme.currentChanged.connect(self.currentSchemeChanged) self.scheme.changed.connect(self.changed) self.baseColorsWidget.changed.connect(self.baseColorsChanged) self.customAttributesWidget.changed.connect(self.customAttributesChanged) self.fontChooser.currentFontChanged.connect(self.fontChanged) self.fontSize.valueChanged.connect(self.fontChanged) self.printScheme.clicked.connect(self.printSchemeChanged) app.translateUI(self) def translateUI(self): self.printScheme.setText(_("Use this scheme for printing")) self.fontLabel.setText(_("Font:")) self.baseColorsItem.setText(0, _("Base Colors")) self.defaultStylesItem.setText(0, _("Default Styles")) self.defaultStyleNames = defaultStyleNames() self.allStyleNames = allStyleNames() for name in textformats.defaultStyles: self.defaultStyles[name].setText(0, self.defaultStyleNames[name]) for group, styles in ly.colorize.default_mapping(): try: n = self.allStyleNames[group][0] except KeyError: n = group self.allStyles[group][0].setText(0, n) for name, base, clss in styles: try: n = self.allStyleNames[group][1][name] except KeyError: n = name self.allStyles[group][1][name].setText(0, n) def currentItemChanged(self, item, previous): if item is self.baseColorsItem: self.stack.setCurrentWidget(self.baseColorsWidget) elif not item.parent(): self.stack.setCurrentWidget(self.emptyWidget) else: data = self.data[self.scheme.currentScheme()] w = self.customAttributesWidget self.stack.setCurrentWidget(w) toptext = None if item.parent() is self.defaultStylesItem: # default style w.setTitle(item.text(0)) w.setTristate(False) w.setTextFormat(data.defaultStyles[item.name]) else: # specific style of specific group group, name = item.parent().group, item.name w.setTitle("{0}: {1}".format(item.parent().text(0), item.text(0))) inherit = item.base if inherit: toptext = _("(Inherits: {name})").format(name=self.defaultStyleNames[inherit]) w.setTristate(bool(inherit)) w.setTextFormat(data.allStyles[group][name]) w.setTopText(toptext) def currentSchemeChanged(self): scheme = self.scheme.currentScheme() if scheme not in self.data: self.data[scheme] = textformats.TextFormatData(scheme) self.updateDisplay() if self.tree.currentItem(): self.currentItemChanged(self.tree.currentItem(), None) with qutil.signalsBlocked(self.printScheme): self.printScheme.setChecked(scheme == self._printScheme) def fontChanged(self): data = self.data[self.scheme.currentScheme()] data.font = self.fontChooser.currentFont() data.font.setPointSizeF(self.fontSize.value()) self.updateDisplay() self.changed.emit() def printSchemeChanged(self): if self.printScheme.isChecked(): self._printScheme = self.scheme.currentScheme() else: self._printScheme = None self.changed.emit() def addSchemeData(self, scheme, tfd): self.data[scheme] = tfd def currentSchemeData(self): return self.data[self.scheme.currentScheme()] def updateDisplay(self): data = self.data[self.scheme.currentScheme()] with qutil.signalsBlocked(self.fontChooser, self.fontSize): self.fontChooser.setCurrentFont(data.font) self.fontSize.setValue(data.font.pointSizeF()) with qutil.signalsBlocked(self): # update base colors for name in textformats.baseColors: self.baseColorsWidget.color[name].setColor(data.baseColors[name]) # update base colors for whole treewidget p = QApplication.palette() p.setColor(QPalette.Base, data.baseColors['background']) p.setColor(QPalette.Text, data.baseColors['text']) p.setColor(QPalette.Highlight, data.baseColors['selectionbackground']) p.setColor(QPalette.HighlightedText, data.baseColors['selectiontext']) self.tree.setPalette(p) def setItemTextFormat(item, f): font = QFont(data.font) if f.hasProperty(QTextFormat.ForegroundBrush): item.setForeground(0, f.foreground().color()) else: item.setForeground(0, data.baseColors['text']) if f.hasProperty(QTextFormat.BackgroundBrush): item.setBackground(0, f.background().color()) else: item.setBackground(0, QBrush()) font.setWeight(f.fontWeight()) font.setItalic(f.fontItalic()) font.setUnderline(f.fontUnderline()) item.setFont(0, font) # update looks of default styles for name in textformats.defaultStyles: setItemTextFormat(self.defaultStyles[name], data.defaultStyles[name]) # update looks of all the specific styles for group, styles in ly.colorize.default_mapping(): children = self.allStyles[group][1] for name, inherit, clss in styles: f = QTextCharFormat(data.defaultStyles[inherit]) if inherit else QTextCharFormat() f.merge(data.allStyles[group][name]) setItemTextFormat(children[name], f) def baseColorsChanged(self, name): # keep data up to date with base colors data = self.data[self.scheme.currentScheme()] data.baseColors[name] = self.baseColorsWidget.color[name].color() self.updateDisplay() self.changed.emit() def customAttributesChanged(self): item = self.tree.currentItem() if not item or not item.parent(): return data = self.data[self.scheme.currentScheme()] if item.parent() is self.defaultStylesItem: # a default style has been changed data.defaultStyles[item.name] = self.customAttributesWidget.textFormat() else: # a specific style has been changed group, name = item.parent().group, item.name data.allStyles[group][name] = self.customAttributesWidget.textFormat() self.updateDisplay() self.changed.emit() def import_(self, filename): from . import import_export import_export.importTheme(filename, self, self.scheme) def export(self, name, filename): from . import import_export try: import_export.exportTheme(self, name, filename) except (IOError, OSError) as e: QMessageBox.critical(self, _("Error"), _( "Can't write to destination:\n\n{url}\n\n{error}").format( url=filename, error=e.strerror)) def loadSettings(self): self.data = {} # holds all data with scheme as key self._printScheme = QSettings().value("printer_scheme", "default", str) self.scheme.loadSettings("editor_scheme", "editor_schemes") def saveSettings(self): self.scheme.saveSettings("editor_scheme", "editor_schemes", "fontscolors") for scheme in self.scheme.schemes(): if scheme in self.data: self.data[scheme].save(scheme) if self._printScheme: QSettings().setValue("printer_scheme", self._printScheme) else: QSettings().remove("printer_scheme")
class TextItemDlg(QDialog): def __init__(self, item=None, position=None, scene=None, parent=None): super(TextItemDlg, self).__init__(parent) self.item = item self.position = position self.scene = scene self.editor = QTextEdit() self.editor.setAcceptRichText(False) self.editor.setTabChangesFocus(True) editorLabel = QLabel("&Text:") editorLabel.setBuddy(self.editor) self.fontComboBox = QFontComboBox() self.fontComboBox.setCurrentFont(QFont("Times", PointSize)) fontLabel = QLabel("&Font:") fontLabel.setBuddy(self.fontComboBox) self.fontSpinBox = QSpinBox() self.fontSpinBox.setAlignment(Qt.AlignRight | Qt.AlignVCenter) self.fontSpinBox.setRange(6, 280) self.fontSpinBox.setValue(PointSize) fontSizeLabel = QLabel("&Size:") fontSizeLabel.setBuddy(self.fontSpinBox) self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False) if self.item is not None: self.editor.setPlainText(self.item.toPlainText()) self.fontComboBox.setCurrentFont(self.item.font()) self.fontSpinBox.setValue(self.item.font().pointSize()) layout = QGridLayout() layout.addWidget(editorLabel, 0, 0) layout.addWidget(self.editor, 1, 0, 1, 6) layout.addWidget(fontLabel, 2, 0) layout.addWidget(self.fontComboBox, 2, 1, 1, 2) layout.addWidget(fontSizeLabel, 2, 3) layout.addWidget(self.fontSpinBox, 2, 4, 1, 2) layout.addWidget(self.buttonBox, 3, 0, 1, 6) self.setLayout(layout) self.fontComboBox.currentFontChanged.connect(self.updateUi) self.fontSpinBox.valueChanged.connect(self.updateUi) self.editor.textChanged.connect(self.updateUi) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.setWindowTitle("Page Designer - {0} Text Item".format( "Add" if self.item is None else "Edit")) self.updateUi() def updateUi(self): font = self.fontComboBox.currentFont() font.setPointSize(self.fontSpinBox.value()) # void QFont::setPointSize(int pointSize) self.editor.document().setDefaultFont(font) # .document(): This property holds the underlying document of the text editor. self.buttonBox.button(QDialogButtonBox.Ok).setEnabled( bool(self.editor.toPlainText())) def accept(self): if self.item is None: self.item = TextItem("", self.position, self.scene) font = self.fontComboBox.currentFont() font.setPointSize(self.fontSpinBox.value()) self.item.setFont(font) self.item.setPlainText(self.editor.toPlainText()) self.item.update() # Schedules a redraw of the area covered by rect in this item. # You can call this function whenever your item needs to be redrawn, such as if it changes appearance or size. global Dirty Dirty = True QDialog.accept(self)
class comic_export_setting_dialog(QDialog): acbfStylesList = [ "speech", "commentary", "formal", "letter", "code", "heading", "audio", "thought", "sign", "sound", "emphasis", "strong" ] def __init__(self): super().__init__() self.setLayout(QVBoxLayout()) self.setWindowTitle(i18n("Export settings")) buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttons.accepted.connect(self.accept) buttons.rejected.connect(self.reject) mainWidget = QTabWidget() self.layout().addWidget(mainWidget) self.layout().addWidget(buttons) # Set basic crop settings # Set which layers to remove before export. mainExportSettings = QWidget() mainExportSettings.setLayout(QVBoxLayout()) groupExportCrop = QGroupBox(i18n("Crop settings")) formCrop = QFormLayout() groupExportCrop.setLayout(formCrop) self.chk_toOutmostGuides = QCheckBox(i18n("Crop to outmost guides")) self.chk_toOutmostGuides.setChecked(True) self.chk_toOutmostGuides.setToolTip( i18n( "This will crop to the outmost guides if possible and otherwise use the underlying crop settings." )) formCrop.addRow("", self.chk_toOutmostGuides) btn_fromSelection = QPushButton( i18n("Set margins from active selection")) btn_fromSelection.clicked.connect(self.slot_set_margin_from_selection) # This doesn't work. formCrop.addRow("", btn_fromSelection) self.spn_marginLeft = QSpinBox() self.spn_marginLeft.setMaximum(99999) self.spn_marginLeft.setSuffix(" px") formCrop.addRow(i18n("Left:"), self.spn_marginLeft) self.spn_marginTop = QSpinBox() self.spn_marginTop.setMaximum(99999) self.spn_marginTop.setSuffix(" px") formCrop.addRow(i18n("Top:"), self.spn_marginTop) self.spn_marginRight = QSpinBox() self.spn_marginRight.setMaximum(99999) self.spn_marginRight.setSuffix(" px") formCrop.addRow(i18n("Right:"), self.spn_marginRight) self.spn_marginBottom = QSpinBox() self.spn_marginBottom.setMaximum(99999) self.spn_marginBottom.setSuffix(" px") formCrop.addRow(i18n("Bottom:"), self.spn_marginBottom) groupExportLayers = QGroupBox(i18n("Layers")) formLayers = QFormLayout() groupExportLayers.setLayout(formLayers) self.cmbLabelsRemove = labelSelector() formLayers.addRow(i18n("Label for removal:"), self.cmbLabelsRemove) self.ln_text_layer_name = QLineEdit() self.ln_text_layer_name.setToolTip( i18n( "These are keywords that can be used to identify text layers. A layer only needs to contain the keyword to be recognised. Keywords should be comma seperated." )) self.ln_panel_layer_name = QLineEdit() self.ln_panel_layer_name.setToolTip( i18n( "These are keywords that can be used to identify panel layers. A layer only needs to contain the keyword to be recognised. Keywords should be comma seperated." )) formLayers.addRow(i18n("Text Layer Key:"), self.ln_text_layer_name) formLayers.addRow(i18n("Panel Layer Key:"), self.ln_panel_layer_name) mainExportSettings.layout().addWidget(groupExportCrop) mainExportSettings.layout().addWidget(groupExportLayers) mainWidget.addTab(mainExportSettings, i18n("General")) # CBZ, crop, resize, which metadata to add. CBZexportSettings = QWidget() CBZexportSettings.setLayout(QVBoxLayout()) self.CBZactive = QCheckBox(i18n("Export to CBZ")) CBZexportSettings.layout().addWidget(self.CBZactive) self.CBZgroupResize = comic_export_resize_widget("CBZ") CBZexportSettings.layout().addWidget(self.CBZgroupResize) self.CBZactive.clicked.connect(self.CBZgroupResize.setEnabled) CBZgroupMeta = QGroupBox(i18n("Metadata to add")) # CBZexportSettings.layout().addWidget(CBZgroupMeta) CBZgroupMeta.setLayout(QFormLayout()) mainWidget.addTab(CBZexportSettings, "CBZ") # ACBF, crop, resize, creator name, version history, panel layer, text layers. ACBFExportSettings = QWidget() ACBFform = QFormLayout() ACBFExportSettings.setLayout(QVBoxLayout()) ACBFdocInfo = QGroupBox() ACBFdocInfo.setTitle(i18n("ACBF Document Info")) ACBFdocInfo.setLayout(ACBFform) self.lnACBFSource = QLineEdit() self.lnACBFSource.setToolTip( i18n( "Whether the acbf file is an adaption of an existing source, and if so, how to find information about that source. So for example, for an adapted webcomic, the official website url should go here." )) self.lnACBFID = QLabel() self.lnACBFID.setToolTip( i18n( "By default this will be filled with a generated universal unique identifier. The ID by itself is merely so that comic book library management programs can figure out if this particular comic is already in their database and whether it has been rated. Of course, the UUID can be changed into something else by manually changing the json, but this is advanced usage." )) self.spnACBFVersion = QSpinBox() self.ACBFhistoryModel = QStandardItemModel() acbfHistoryList = QListView() acbfHistoryList.setModel(self.ACBFhistoryModel) btn_add_history = QPushButton(i18n("Add history entry")) btn_add_history.clicked.connect(self.slot_add_history_item) self.chkIncludeTranslatorComments = QCheckBox() self.chkIncludeTranslatorComments.setText( i18n("Include Translator's Comments")) self.chkIncludeTranslatorComments.setToolTip( i18n( "A PO file can contain translator's comments. If this is checked, the translations comments will be added as references into the ACBF file." )) self.lnTranslatorHeader = QLineEdit() ACBFform.addRow(i18n("Source:"), self.lnACBFSource) ACBFform.addRow(i18n("ACBF UID:"), self.lnACBFID) ACBFform.addRow(i18n("Version:"), self.spnACBFVersion) ACBFform.addRow(i18n("Version History:"), acbfHistoryList) ACBFform.addRow("", btn_add_history) ACBFform.addRow("", self.chkIncludeTranslatorComments) ACBFform.addRow(i18n("Translator Header:"), self.lnTranslatorHeader) ACBFAuthorInfo = QWidget() acbfAVbox = QVBoxLayout(ACBFAuthorInfo) infoLabel = QLabel( i18n( "The people responsible for the generation of the CBZ/ACBF files." )) infoLabel.setWordWrap(True) ACBFAuthorInfo.layout().addWidget(infoLabel) self.ACBFauthorModel = QStandardItemModel(0, 6) labels = [ i18n("Nick Name"), i18n("Given Name"), i18n("Middle Name"), i18n("Family Name"), i18n("Email"), i18n("Homepage") ] self.ACBFauthorModel.setHorizontalHeaderLabels(labels) self.ACBFauthorTable = QTableView() acbfAVbox.addWidget(self.ACBFauthorTable) self.ACBFauthorTable.setModel(self.ACBFauthorModel) self.ACBFauthorTable.verticalHeader().setDragEnabled(True) self.ACBFauthorTable.verticalHeader().setDropIndicatorShown(True) self.ACBFauthorTable.verticalHeader().setSectionsMovable(True) self.ACBFauthorTable.verticalHeader().sectionMoved.connect( self.slot_reset_author_row_visual) AuthorButtons = QHBoxLayout() btn_add_author = QPushButton(i18n("Add author")) btn_add_author.clicked.connect(self.slot_add_author) AuthorButtons.addWidget(btn_add_author) btn_remove_author = QPushButton(i18n("Remove author")) btn_remove_author.clicked.connect(self.slot_remove_author) AuthorButtons.addWidget(btn_remove_author) acbfAVbox.addLayout(AuthorButtons) ACBFStyle = QWidget() ACBFStyle.setLayout(QHBoxLayout()) self.ACBFStylesModel = QStandardItemModel() self.ACBFStyleClass = QListView() self.ACBFStyleClass.setModel(self.ACBFStylesModel) ACBFStyle.layout().addWidget(self.ACBFStyleClass) ACBFStyleEdit = QWidget() ACBFStyleEditVB = QVBoxLayout(ACBFStyleEdit) self.ACBFfontCombo = QFontComboBox() self.ACBFdefaultFont = QComboBox() self.ACBFdefaultFont.addItems( ["sans-serif", "serif", "monospace", "cursive", "fantasy"]) self.ACBFBold = QCheckBox(i18n("Bold")) self.ACBFItal = QCheckBox(i18n("Italic")) self.ACBFStyleClass.clicked.connect(self.slot_set_style) self.ACBFStyleClass.selectionModel().selectionChanged.connect( self.slot_set_style) self.ACBFStylesModel.itemChanged.connect(self.slot_set_style) self.ACBFfontCombo.currentFontChanged.connect( self.slot_font_current_style) self.ACBFfontCombo.setEditable(False) self.ACBFBold.toggled.connect(self.slot_font_current_style) self.ACBFItal.toggled.connect(self.slot_font_current_style) colorWidget = QGroupBox(self) colorWidget.setTitle(i18n("Text Colors")) colorWidget.setLayout(QVBoxLayout()) self.regularColor = QColorDialog() self.invertedColor = QColorDialog() self.btn_acbfRegColor = QPushButton(i18n("Regular Text"), self) self.btn_acbfRegColor.clicked.connect(self.slot_change_regular_color) self.btn_acbfInvColor = QPushButton(i18n("Inverted Text"), self) self.btn_acbfInvColor.clicked.connect(self.slot_change_inverted_color) colorWidget.layout().addWidget(self.btn_acbfRegColor) colorWidget.layout().addWidget(self.btn_acbfInvColor) ACBFStyleEditVB.addWidget(colorWidget) ACBFStyleEditVB.addWidget(self.ACBFfontCombo) ACBFStyleEditVB.addWidget(self.ACBFdefaultFont) ACBFStyleEditVB.addWidget(self.ACBFBold) ACBFStyleEditVB.addWidget(self.ACBFItal) ACBFStyleEditVB.addStretch() ACBFStyle.layout().addWidget(ACBFStyleEdit) ACBFTabwidget = QTabWidget() ACBFTabwidget.addTab(ACBFdocInfo, i18n("Document Info")) ACBFTabwidget.addTab(ACBFAuthorInfo, i18n("Author Info")) ACBFTabwidget.addTab(ACBFStyle, i18n("Style Sheet")) ACBFExportSettings.layout().addWidget(ACBFTabwidget) mainWidget.addTab(ACBFExportSettings, i18n("ACBF")) # Epub export, crop, resize, other questions. EPUBexportSettings = QWidget() EPUBexportSettings.setLayout(QVBoxLayout()) self.EPUBactive = QCheckBox(i18n("Export to EPUB")) EPUBexportSettings.layout().addWidget(self.EPUBactive) self.EPUBgroupResize = comic_export_resize_widget("EPUB") EPUBexportSettings.layout().addWidget(self.EPUBgroupResize) self.EPUBactive.clicked.connect(self.EPUBgroupResize.setEnabled) mainWidget.addTab(EPUBexportSettings, "EPUB") # For Print. Crop, no resize. TIFFExportSettings = QWidget() TIFFExportSettings.setLayout(QVBoxLayout()) self.TIFFactive = QCheckBox(i18n("Export to TIFF")) TIFFExportSettings.layout().addWidget(self.TIFFactive) self.TIFFgroupResize = comic_export_resize_widget("TIFF") TIFFExportSettings.layout().addWidget(self.TIFFgroupResize) self.TIFFactive.clicked.connect(self.TIFFgroupResize.setEnabled) mainWidget.addTab(TIFFExportSettings, "TIFF") # SVG, crop, resize, embed vs link. #SVGExportSettings = QWidget() #mainWidget.addTab(SVGExportSettings, "SVG") """ Add a history item to the acbf version history list. """ def slot_add_history_item(self): newItem = QStandardItem() newItem.setText("v" + str(self.spnACBFVersion.value()) + "-" + i18n("in this version...")) self.ACBFhistoryModel.appendRow(newItem) """ Get the margins by treating the active selection in a document as the trim area. This allows people to snap selections to a vector or something, and then get the margins. """ def slot_set_margin_from_selection(self): doc = Application.activeDocument() if doc is not None: if doc.selection() is not None: self.spn_marginLeft.setValue(doc.selection().x()) self.spn_marginTop.setValue(doc.selection().y()) self.spn_marginRight.setValue(doc.width() - (doc.selection().x() + doc.selection().width())) self.spn_marginBottom.setValue(doc.height() - (doc.selection().y() + doc.selection().height())) """ Add an author with default values initialised. """ def slot_add_author(self): listItems = [] listItems.append(QStandardItem(i18n("Anon"))) # Nick name listItems.append(QStandardItem(i18n("John"))) # First name listItems.append(QStandardItem()) # Middle name listItems.append(QStandardItem(i18n("Doe"))) # Last name listItems.append(QStandardItem()) # email listItems.append(QStandardItem()) # homepage self.ACBFauthorModel.appendRow(listItems) """ Remove the selected author from the author list. """ def slot_remove_author(self): self.ACBFauthorModel.removeRow( self.ACBFauthorTable.currentIndex().row()) """ Ensure that the drag and drop of authors doesn't mess up the labels. """ def slot_reset_author_row_visual(self): headerLabelList = [] for i in range(self.ACBFauthorTable.verticalHeader().count()): headerLabelList.append(str(i)) for i in range(self.ACBFauthorTable.verticalHeader().count()): logicalI = self.ACBFauthorTable.verticalHeader().logicalIndex(i) headerLabelList[logicalI] = str(i + 1) self.ACBFauthorModel.setVerticalHeaderLabels(headerLabelList) def slot_set_style(self): index = self.ACBFStyleClass.currentIndex() if index.isValid(): item = self.ACBFStylesModel.item(index.row()) font = QFont() font.setFamily(str(item.data(role=Qt.UserRole + 1))) self.ACBFfontCombo.setCurrentFont(font) self.ACBFdefaultFont.setCurrentText( str(item.data(role=Qt.UserRole + 2))) bold = item.data(role=Qt.UserRole + 3) if bold is not None: self.ACBFBold.setChecked(bold) else: self.ACBFBold.setChecked(False) italic = item.data(role=Qt.UserRole + 4) if italic is not None: self.ACBFItal.setChecked(italic) else: self.ACBFItal.setChecked(False) 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 slot_change_regular_color(self): if (self.regularColor.exec_() == QDialog.Accepted): square = QPixmap(32, 32) square.fill(self.regularColor.currentColor()) self.btn_acbfRegColor.setIcon(QIcon(square)) def slot_change_inverted_color(self): if (self.invertedColor.exec_() == QDialog.Accepted): square = QPixmap(32, 32) square.fill(self.invertedColor.currentColor()) self.btn_acbfInvColor.setIcon(QIcon(square)) """ Load the UI values from the config dictionary given. """ def setConfig(self, config): if "cropToGuides" in config.keys(): self.chk_toOutmostGuides.setChecked(config["cropToGuides"]) if "cropLeft" in config.keys(): self.spn_marginLeft.setValue(config["cropLeft"]) if "cropTop" in config.keys(): self.spn_marginTop.setValue(config["cropTop"]) if "cropRight" in config.keys(): self.spn_marginRight.setValue(config["cropRight"]) if "cropBottom" in config.keys(): self.spn_marginBottom.setValue(config["cropBottom"]) if "labelsToRemove" in config.keys(): self.cmbLabelsRemove.setLabels(config["labelsToRemove"]) if "textLayerNames" in config.keys(): self.ln_text_layer_name.setText(", ".join( config["textLayerNames"])) else: self.ln_text_layer_name.setText("text") if "panelLayerNames" in config.keys(): self.ln_panel_layer_name.setText(", ".join( config["panelLayerNames"])) else: self.ln_panel_layer_name.setText("panels") self.CBZgroupResize.set_config(config) if "CBZactive" in config.keys(): self.CBZactive.setChecked(config["CBZactive"]) self.EPUBgroupResize.set_config(config) if "EPUBactive" in config.keys(): self.EPUBactive.setChecked(config["EPUBactive"]) self.TIFFgroupResize.set_config(config) if "TIFFactive" in config.keys(): self.TIFFactive.setChecked(config["TIFFactive"]) if "acbfAuthor" in config.keys(): if isinstance(config["acbfAuthor"], list): for author in config["acbfAuthor"]: listItems = [] listItems.append(QStandardItem(author.get("nickname", ""))) listItems.append( QStandardItem(author.get("first-name", ""))) listItems.append(QStandardItem(author.get("initials", ""))) listItems.append(QStandardItem(author.get("last-name", ""))) listItems.append(QStandardItem(author.get("email", ""))) listItems.append(QStandardItem(author.get("homepage", ""))) self.ACBFauthorModel.appendRow(listItems) pass else: listItems = [] listItems.append(QStandardItem( config["acbfAuthor"])) # Nick name for i in range(0, 5): listItems.append(QStandardItem()) # First name self.ACBFauthorModel.appendRow(listItems) if "acbfSource" in config.keys(): self.lnACBFSource.setText(config["acbfSource"]) if "acbfID" in config.keys(): self.lnACBFID.setText(config["acbfID"]) else: self.lnACBFID.setText(QUuid.createUuid().toString()) if "acbfVersion" in config.keys(): self.spnACBFVersion.setValue(config["acbfVersion"]) if "acbfHistory" in config.keys(): for h in config["acbfHistory"]: item = QStandardItem() item.setText(h) self.ACBFhistoryModel.appendRow(item) if "acbfStyles" in config.keys(): styleDict = config.get("acbfStyles", {}) for key in self.acbfStylesList: keyDict = styleDict.get(key, {}) style = QStandardItem(key.title()) style.setCheckable(True) if key in styleDict.keys(): style.setCheckState(Qt.Checked) else: style.setCheckState(Qt.Unchecked) style.setData(keyDict.get("font", QFont().family()), role=Qt.UserRole + 1) style.setData(keyDict.get("genericfont", "sans-serif"), role=Qt.UserRole + 2) style.setData(keyDict.get("bold", False), role=Qt.UserRole + 3) style.setData(keyDict.get("ital", False), role=Qt.UserRole + 4) self.ACBFStylesModel.appendRow(style) keyDict = styleDict.get("general", {}) self.regularColor.setCurrentColor( QColor(keyDict.get("color", "#000000"))) square = QPixmap(32, 32) square.fill(self.regularColor.currentColor()) self.btn_acbfRegColor.setIcon(QIcon(square)) keyDict = styleDict.get("inverted", {}) self.invertedColor.setCurrentColor( QColor(keyDict.get("color", "#FFFFFF"))) square.fill(self.invertedColor.currentColor()) self.btn_acbfInvColor.setIcon(QIcon(square)) else: for key in self.acbfStylesList: style = QStandardItem(key.title()) style.setCheckable(True) style.setCheckState(Qt.Unchecked) style.setData(QFont().family(), role=Qt.UserRole + 1) style.setData("sans-serif", role=Qt.UserRole + 2) style.setData(False, role=Qt.UserRole + 3) #Bold style.setData(False, role=Qt.UserRole + 4) #Italic self.ACBFStylesModel.appendRow(style) self.CBZgroupResize.setEnabled(self.CBZactive.isChecked()) self.lnTranslatorHeader.setText( config.get("translatorHeader", "Translator's Notes")) self.chkIncludeTranslatorComments.setChecked( config.get("includeTranslComment", False)) """ Store the GUI values into the config dictionary given. @return the config diactionary filled with new values. """ def getConfig(self, config): config["cropToGuides"] = self.chk_toOutmostGuides.isChecked() config["cropLeft"] = self.spn_marginLeft.value() config["cropTop"] = self.spn_marginTop.value() config["cropBottom"] = self.spn_marginRight.value() config["cropRight"] = self.spn_marginBottom.value() config["labelsToRemove"] = self.cmbLabelsRemove.getLabels() config["CBZactive"] = self.CBZactive.isChecked() config = self.CBZgroupResize.get_config(config) config["EPUBactive"] = self.EPUBactive.isChecked() config = self.EPUBgroupResize.get_config(config) config["TIFFactive"] = self.TIFFactive.isChecked() config = self.TIFFgroupResize.get_config(config) authorList = [] for row in range(self.ACBFauthorTable.verticalHeader().count()): logicalIndex = self.ACBFauthorTable.verticalHeader().logicalIndex( row) listEntries = [ "nickname", "first-name", "initials", "last-name", "email", "homepage" ] author = {} for i in range(len(listEntries)): entry = self.ACBFauthorModel.data( self.ACBFauthorModel.index(logicalIndex, i)) if entry is None: entry = " " if entry.isspace() is False and len(entry) > 0: author[listEntries[i]] = entry elif listEntries[i] in author.keys(): author.pop(listEntries[i]) authorList.append(author) config["acbfAuthor"] = authorList config["acbfSource"] = self.lnACBFSource.text() config["acbfID"] = self.lnACBFID.text() config["acbfVersion"] = self.spnACBFVersion.value() versionList = [] for r in range(self.ACBFhistoryModel.rowCount()): index = self.ACBFhistoryModel.index(r, 0) versionList.append( self.ACBFhistoryModel.data(index, Qt.DisplayRole)) config["acbfHistory"] = versionList acbfStylesDict = {} for row in range(0, self.ACBFStylesModel.rowCount()): entry = self.ACBFStylesModel.item(row) if entry.checkState() == Qt.Checked: key = entry.text().lower() style = {} font = entry.data(role=Qt.UserRole + 1) if font is not None: style["font"] = font genericfont = entry.data(role=Qt.UserRole + 2) if font is not None: style["genericfont"] = genericfont bold = entry.data(role=Qt.UserRole + 3) if bold is not None: style["bold"] = bold italic = entry.data(role=Qt.UserRole + 4) if italic is not None: style["ital"] = italic acbfStylesDict[key] = style acbfStylesDict["general"] = { "color": self.regularColor.currentColor().name() } acbfStylesDict["inverted"] = { "color": self.invertedColor.currentColor().name() } config["acbfStyles"] = acbfStylesDict config["translatorHeader"] = self.lnTranslatorHeader.text() config[ "includeTranslComment"] = self.chkIncludeTranslatorComments.isChecked( ) # Turn this into something that retreives from a line-edit when string freeze is over. config["textLayerNames"] = self.ln_text_layer_name.text().split(",") config["panelLayerNames"] = self.ln_panel_layer_name.text().split(",") return config
class MainWindow(QMainWindow): InsertTextButton = 10 items = {-2: "source", -3: "channel", -4: "sink"} def __init__(self): import _diagramscene_rc super(MainWindow, self).__init__() self.config_manipulations = FlumeConfig(self) properties_generator.dump_props() self.create_actions() self.create_menus() self.create_tool_box() self.clicked_button_id = 0 self.scene = DiagramScene(self.item_menu) self.scene.setSceneRect(QRectF(0, 0, 5000, 5000)) self.scene.itemInserted.connect(self.item_inserted) self.scene.textInserted.connect(self.text_inserted) self.scene.itemSelected.connect(self.item_selected) self.create_tool_bars() # self.scene.enable_grid() layout = QHBoxLayout() layout.addWidget(self.tool_box) self.view = QGraphicsView(self.scene) self.view.centerOn(0, 0) layout.addWidget(self.view) self.widget = QWidget() self.widget.setLayout(layout) self.setCentralWidget(self.widget) self.setWindowTitle("The Flume Illustrator") # noinspection PyAttributeOutsideInit,PyArgumentList def create_actions(self): self.to_front_action = QAction(QIcon(':/images/bringtofront.png'), "Bring to &Front", self, shortcut="Ctrl+F", statusTip="Bring item to front", triggered=self.bring_to_front) self.send_back_action = QAction(QIcon(':/images/sendtoback.png'), "Send to &Back", self, shortcut="Ctrl+B", statusTip="Send item to back", triggered=self.send_to_back) self.bold_action = QAction(QIcon(':/images/bold.png'), "Bold", self, checkable=True, shortcut="Ctrl+B", triggered=self.handle_font_change) self.italic_action = QAction(QIcon(':/images/italic.png'), "Italic", self, checkable=True, shortcut="Ctrl+I", triggered=self.handle_font_change) self.underline_action = QAction(QIcon(':/images/underline.png'), "Underline", self, checkable=True, shortcut="Ctrl+U", triggered=self.handle_font_change) self.delete_action = QAction(QIcon(':/images/delete.png'), "Delete", self, shortcut="Delete", statusTip='Delete item from diagram', triggered=self.delete_item) self.exit_action = QAction("Exit", self, shortcut="Ctrl+X", statusTip="Quit program", triggered=self.close) self.about_action = QAction("About", self, shortcut="Ctrl+B", triggered=self.about) self.load_config_action = QAction("Load", self, shortcut="Ctrl+O", statusTip="Load config file", triggered=self.config_manipulations.load_config) self.enable_grid_action = QAction("Enable grid", self, checkable=True, triggered=self.enable_grid) # noinspection PyAttributeOutsideInit def create_menus(self): self.file_menu = self.menuBar().addMenu("File") self.file_menu.addAction(self.load_config_action) self.file_menu.addAction(self.exit_action) self.item_menu = self.menuBar().addMenu("Item") self.item_menu.addAction(self.delete_action) self.item_menu.addSeparator() self.item_menu.addAction(self.to_front_action) self.item_menu.addAction(self.send_back_action) self.about_menu = self.menuBar().addMenu("Help") self.about_menu.addAction(self.about_action) # noinspection PyAttributeOutsideInit,PyUnresolvedReferences def create_tool_box(self): self.button_group = QButtonGroup() self.button_group.setExclusive(False) self.button_group.buttonClicked[int].connect(self.button_group_clicked) layout = QGridLayout() layout.addWidget(self.create_cell_widget("Source", "source"), 0, 0) layout.addWidget(self.create_cell_widget("Channel", "channel"), 0, 1) layout.addWidget(self.create_cell_widget("Sink", "sink"), 1, 0) text_button = QToolButton() text_button.setCheckable(True) self.button_group.addButton(text_button, self.InsertTextButton) text_button.setIcon(QIcon(QPixmap(':/images/textpointer.png').scaled(30, 30))) text_button.setIconSize(QSize(50, 50)) text_layout = QGridLayout() text_layout.addWidget(text_button, 0, 0, Qt.AlignHCenter) text_layout.addWidget(QLabel("Text"), 1, 0, Qt.AlignCenter) text_widget = QWidget() text_widget.setLayout(text_layout) layout.addWidget(text_widget, 1, 1) layout.setRowStretch(3, 10) layout.setColumnStretch(2, 10) item_widget = QWidget() item_widget.setLayout(layout) self.tool_box = QToolBox() self.tool_box.setSizePolicy(QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Ignored)) self.tool_box.setMinimumWidth(item_widget.sizeHint().width()) self.tool_box.addItem(item_widget, "Basic Flume Items") # noinspection PyAttributeOutsideInit,PyUnresolvedReferences def create_tool_bars(self): self.edit_tool_bar = self.addToolBar("Edit") self.edit_tool_bar.addAction(self.delete_action) self.edit_tool_bar.addAction(self.to_front_action) self.edit_tool_bar.addAction(self.send_back_action) self.edit_tool_bar.addAction(self.enable_grid_action) self.font_combo = QFontComboBox() self.font_combo.currentFontChanged.connect(self.current_font_changed) self.font_size_combo = QComboBox() self.font_size_combo.setEditable(True) for i in range(8, 30, 2): self.font_size_combo.addItem(str(i)) validator = QIntValidator(2, 64, self) self.font_size_combo.setValidator(validator) self.font_size_combo.currentIndexChanged.connect(self.font_size_changed) self.font_color_tool_button = QToolButton() self.font_color_tool_button.setPopupMode(QToolButton.MenuButtonPopup) self.font_color_tool_button.setMenu( self.create_color_menu(self.text_color_changed, Qt.black)) self.text_action = self.font_color_tool_button.menu().defaultAction() self.font_color_tool_button.setIcon( self.create_color_tool_button_icon(':/images/textpointer.png', Qt.black)) self.font_color_tool_button.setAutoFillBackground(True) self.font_color_tool_button.clicked.connect(self.text_button_triggered) self.fill_color_tool_button = QToolButton() self.fill_color_tool_button.setPopupMode(QToolButton.MenuButtonPopup) self.fill_color_tool_button.setMenu( self.create_color_menu(self.item_color_changed, Qt.white)) self.fillAction = self.fill_color_tool_button.menu().defaultAction() self.fill_color_tool_button.setIcon( self.create_color_tool_button_icon(':/images/floodfill.png', Qt.white)) self.fill_color_tool_button.clicked.connect(self.fill_button_triggered) self.line_color_tool_button = QToolButton() self.line_color_tool_button.setPopupMode(QToolButton.MenuButtonPopup) self.line_color_tool_button.setMenu( self.create_color_menu(self.line_color_changed, Qt.black)) self.lineAction = self.line_color_tool_button.menu().defaultAction() self.line_color_tool_button.setIcon( self.create_color_tool_button_icon(':/images/linecolor.png', Qt.black)) self.line_color_tool_button.clicked.connect(self.line_button_triggered) self.text_tool_bar = self.addToolBar("Font") self.text_tool_bar.addWidget(self.font_combo) self.text_tool_bar.addWidget(self.font_size_combo) self.text_tool_bar.addAction(self.bold_action) self.text_tool_bar.addAction(self.italic_action) self.text_tool_bar.addAction(self.underline_action) self.color_tool_bar = self.addToolBar("Color") self.color_tool_bar.addWidget(self.font_color_tool_button) self.color_tool_bar.addWidget(self.fill_color_tool_button) self.color_tool_bar.addWidget(self.line_color_tool_button) self.loading_tool_bar = self.addToolBar("Load") self.loading_tool_bar.addAction(self.load_config_action) pointer_button = QToolButton() pointer_button.setCheckable(True) pointer_button.setChecked(True) pointer_button.setIcon(QIcon(":/images/pointer.png")) line_pointer_button = QToolButton() line_pointer_button.setCheckable(True) line_pointer_button.setIcon(QIcon(":/images/linepointer.png")) self.pointer_type_group = QButtonGroup() self.pointer_type_group.addButton(pointer_button, DiagramScene.MoveItem) self.pointer_type_group.addButton(line_pointer_button, DiagramScene.InsertLine) self.pointer_type_group.buttonClicked[int].connect(self.pointer_group_clicked) self.scene_scale_combo = QComboBox() self.scene_scale_combo.addItems(["50%", "75%", "100%", "125%", "150%"]) self.scene_scale_combo.setCurrentIndex(2) self.scene_scale_combo.currentIndexChanged[str].connect(self.scene_scale_changed) self.pointer_tool_bar = self.addToolBar("Pointer type") self.pointer_tool_bar.addWidget(pointer_button) self.pointer_tool_bar.addWidget(line_pointer_button) self.pointer_tool_bar.addWidget(self.scene_scale_combo) def button_group_clicked(self, button_id): buttons = self.button_group.buttons() self.clicked_button_id = button_id for button in buttons: if self.button_group.button(button_id) != button: button.setChecked(False) if button_id == self.InsertTextButton: self.scene.set_mode(DiagramScene.InsertText) else: self.scene.set_item_type(self.items[button_id]) self.scene.set_mode(DiagramScene.InsertItem) def delete_item(self): for item in self.scene.selectedItems(): if isinstance(item, FlumeDiagramItem): item.remove_arrows() self.scene.removeItem(item) # noinspection PyTypeChecker,PyCallByClass def about(self): # noinspection PyArgumentList QMessageBox.about(self, "About Flume Illustrator", "The Flume illustrator shows config-file details") def pointer_group_clicked(self): self.scene.set_mode(self.pointer_type_group.checkedId()) def bring_to_front(self): if not self.scene.selectedItems(): return selected_item = self.scene.selectedItems()[0] overlap_items = selected_item.collidingItems() z_value = 0 for item in overlap_items: if item.zValue() >= z_value and isinstance(item, FlumeDiagramItem): z_value = item.zValue() + 0.1 selected_item.setZValue(z_value) def send_to_back(self): if not self.scene.selectedItems(): return selected_item = self.scene.selectedItems()[0] overlap_items = selected_item.collidingItems() z_value = 0 for item in overlap_items: if item.zValue() <= z_value and isinstance(item, FlumeDiagramItem): z_value = item.zValue() - 0.1 selected_item.setZValue(z_value) def scene_scale_changed(self, scale): new_scale = float(scale[:scale.index("%")]) / 100 old_transform = self.view.transform() self.view.resetTransform() self.view.translate(old_transform.dx(), old_transform.dy()) self.view.scale(new_scale, new_scale) def item_inserted(self, diagram_type): self.pointer_type_group.button(DiagramScene.MoveItem).setChecked(True) self.scene.set_mode(self.scene.DefaultMode) self.button_group.button(self.clicked_button_id).setChecked(False) def text_inserted(self, item): self.button_group.button(self.InsertTextButton).setChecked(False) self.scene.set_mode(self.pointer_type_group.checkedId()) def current_font_changed(self, font): self.handle_font_change() def font_size_changed(self, font=None): self.handle_font_change() def text_color_changed(self): self.text_action = self.sender() self.font_color_tool_button.setIcon( self.create_color_tool_button_icon(':/images/textpointer.png', QColor(self.text_action.data()))) self.text_button_triggered() def item_color_changed(self): self.fillAction = self.sender() self.fill_color_tool_button.setIcon( self.create_color_tool_button_icon(':/images/floodfill.png', QColor(self.fillAction.data()))) self.fill_button_triggered() def line_color_changed(self): self.lineAction = self.sender() self.line_color_tool_button.setIcon( self.create_color_tool_button_icon(':/images/linecolor.png', QColor(self.lineAction.data()))) self.line_button_triggered() def text_button_triggered(self): self.scene.set_text_color(QColor(self.text_action.data())) def fill_button_triggered(self): self.scene.set_item_color(QColor(self.fillAction.data())) def line_button_triggered(self): self.scene.set_line_color(QColor(self.lineAction.data())) def handle_font_change(self): font = self.font_combo.currentFont() font.setPointSize(int(self.font_size_combo.currentText())) if self.bold_action.isChecked(): font.setWeight(QFont.Bold) else: font.setWeight(QFont.Normal) font.setItalic(self.italic_action.isChecked()) font.setUnderline(self.underline_action.isChecked()) self.scene.setFont(font) def item_selected(self, item): font = item.font() self.font_combo.setCurrentFont(font) self.font_size_combo.setEditText(str(font.pointSize())) self.bold_action.setChecked(font.weight() == QFont.Bold) self.italic_action.setChecked(font.italic()) self.underline_action.setChecked(font.underline()) def create_cell_widget(self, text, diagram_type): item = FlumeObject(diagram_type, "") icon = QIcon(item.pictogram.image()) button = QToolButton() button.setIcon(icon) button.setIconSize(QSize(50, 50)) button.setCheckable(True) self.button_group.addButton(button) # , diagram_type layout = QGridLayout() layout.addWidget(button, 0, 0, Qt.AlignHCenter) layout.addWidget(QLabel(text), 1, 0, Qt.AlignHCenter) widget = QWidget() widget.setLayout(layout) return widget # noinspection PyArgumentList def create_color_menu(self, slot, default_color): colors = [Qt.black, Qt.white, Qt.red, Qt.blue, Qt.yellow] names = ["black", "white", "red", "blue", "yellow"] color_menu = QMenu(self) for color, name in zip(colors, names): action = QAction(self.create_color_icon(color), name, self, triggered=slot) action.setData(QColor(color)) color_menu.addAction(action) if color == default_color: color_menu.setDefaultAction(action) return color_menu @staticmethod def create_color_tool_button_icon(image_file, color): pixmap = QPixmap(50, 80) pixmap.fill(Qt.transparent) painter = QPainter(pixmap) image = QPixmap(image_file) target = QRect(0, 0, 50, 60) source = QRect(0, 0, 42, 42) painter.fillRect(QRect(0, 60, 50, 80), color) painter.drawPixmap(target, image, source) painter.end() return QIcon(pixmap) @staticmethod def create_color_icon(color): pixmap = QPixmap(20, 20) painter = QPainter(pixmap) painter.setPen(Qt.NoPen) painter.fillRect(QRect(0, 0, 20, 20), color) painter.end() return QIcon(pixmap) def enable_grid(self): if self.enable_grid_action.isChecked(): color = Qt.black else: color = Qt.white for i in range(50): for j in range(50): self.scene.addEllipse(i * 100, j * 100, 2, 2, QPen(color))
class FontsColors(preferences.Page): def __init__(self, dialog): super(FontsColors, self).__init__(dialog) layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) self.scheme = SchemeSelector(self) layout.addWidget(self.scheme) self.printScheme = QCheckBox() layout.addWidget(self.printScheme) hbox = QHBoxLayout() self.tree = QTreeWidget(self) self.tree.setHeaderHidden(True) self.tree.setAnimated(True) self.stack = QStackedWidget(self) hbox.addWidget(self.tree) hbox.addWidget(self.stack) layout.addLayout(hbox) hbox = QHBoxLayout() self.fontLabel = QLabel() self.fontChooser = QFontComboBox() self.fontSize = QDoubleSpinBox() self.fontSize.setRange(6.0, 32.0) self.fontSize.setSingleStep(0.5) self.fontSize.setDecimals(1) hbox.addWidget(self.fontLabel) hbox.addWidget(self.fontChooser, 1) hbox.addWidget(self.fontSize) layout.addLayout(hbox) # add the items to our list self.baseColorsItem = i = QTreeWidgetItem() self.tree.addTopLevelItem(i) self.defaultStylesItem = i = QTreeWidgetItem() self.tree.addTopLevelItem(i) self.defaultStyles = {} for name in textformats.defaultStyles: self.defaultStyles[name] = i = QTreeWidgetItem() self.defaultStylesItem.addChild(i) i.name = name self.defaultStylesItem.setExpanded(True) self.allStyles = {} for group, styles in ly.colorize.default_mapping(): i = QTreeWidgetItem() children = {} self.allStyles[group] = (i, children) self.tree.addTopLevelItem(i) i.group = group for name, base, clss in styles: j = QTreeWidgetItem() j.name = name j.base = base i.addChild(j) children[name] = j self.baseColorsWidget = BaseColors(self) self.customAttributesWidget = CustomAttributes(self) self.emptyWidget = QWidget(self) self.stack.addWidget(self.baseColorsWidget) self.stack.addWidget(self.customAttributesWidget) self.stack.addWidget(self.emptyWidget) self.tree.currentItemChanged.connect(self.currentItemChanged) self.tree.setCurrentItem(self.baseColorsItem) self.scheme.currentChanged.connect(self.currentSchemeChanged) self.scheme.changed.connect(self.changed) self.baseColorsWidget.changed.connect(self.baseColorsChanged) self.customAttributesWidget.changed.connect( self.customAttributesChanged) self.fontChooser.currentFontChanged.connect(self.fontChanged) self.fontSize.valueChanged.connect(self.fontChanged) self.printScheme.clicked.connect(self.printSchemeChanged) app.translateUI(self) def translateUI(self): self.printScheme.setText(_("Use this scheme for printing")) self.fontLabel.setText(_("Font:")) self.baseColorsItem.setText(0, _("Base Colors")) self.defaultStylesItem.setText(0, _("Default Styles")) self.defaultStyleNames = defaultStyleNames() self.allStyleNames = allStyleNames() for name in textformats.defaultStyles: self.defaultStyles[name].setText(0, self.defaultStyleNames[name]) for group, styles in ly.colorize.default_mapping(): self.allStyles[group][0].setText(0, self.allStyleNames[group][0]) for name, base, clss in styles: self.allStyles[group][1][name].setText( 0, self.allStyleNames[group][1][name]) def currentItemChanged(self, item, previous): if item is self.baseColorsItem: self.stack.setCurrentWidget(self.baseColorsWidget) elif not item.parent(): self.stack.setCurrentWidget(self.emptyWidget) else: data = self.data[self.scheme.currentScheme()] w = self.customAttributesWidget self.stack.setCurrentWidget(w) toptext = None if item.parent() is self.defaultStylesItem: # default style w.setTitle(item.text(0)) w.setTristate(False) w.setTextFormat(data.defaultStyles[item.name]) else: # specific style of specific group group, name = item.parent().group, item.name w.setTitle("{0}: {1}".format(item.parent().text(0), item.text(0))) inherit = item.base if inherit: toptext = _("(Inherits: {name})").format( name=self.defaultStyleNames[inherit]) w.setTristate(bool(inherit)) w.setTextFormat(data.allStyles[group][name]) w.setTopText(toptext) def currentSchemeChanged(self): scheme = self.scheme.currentScheme() if scheme not in self.data: self.data[scheme] = textformats.TextFormatData(scheme) self.updateDisplay() if self.tree.currentItem(): self.currentItemChanged(self.tree.currentItem(), None) with qutil.signalsBlocked(self.printScheme): self.printScheme.setChecked(scheme == self._printScheme) def fontChanged(self): data = self.data[self.scheme.currentScheme()] data.font = self.fontChooser.currentFont() data.font.setPointSizeF(self.fontSize.value()) self.updateDisplay() self.changed.emit() def printSchemeChanged(self): if self.printScheme.isChecked(): self._printScheme = self.scheme.currentScheme() else: self._printScheme = None self.changed.emit() def addSchemeData(self, scheme, tfd): self.data[scheme] = tfd def currentSchemeData(self): return self.data[self.scheme.currentScheme()] def updateDisplay(self): data = self.data[self.scheme.currentScheme()] with qutil.signalsBlocked(self.fontChooser, self.fontSize): self.fontChooser.setCurrentFont(data.font) self.fontSize.setValue(data.font.pointSizeF()) with qutil.signalsBlocked(self): # update base colors for name in textformats.baseColors: self.baseColorsWidget.color[name].setColor( data.baseColors[name]) # update base colors for whole treewidget p = QApplication.palette() p.setColor(QPalette.Base, data.baseColors['background']) p.setColor(QPalette.Text, data.baseColors['text']) p.setColor(QPalette.Highlight, data.baseColors['selectionbackground']) p.setColor(QPalette.HighlightedText, data.baseColors['selectiontext']) self.tree.setPalette(p) def setItemTextFormat(item, f): font = QFont(data.font) if f.hasProperty(QTextFormat.ForegroundBrush): item.setForeground(0, f.foreground().color()) else: item.setForeground(0, data.baseColors['text']) if f.hasProperty(QTextFormat.BackgroundBrush): item.setBackground(0, f.background().color()) else: item.setBackground(0, QBrush()) font.setWeight(f.fontWeight()) font.setItalic(f.fontItalic()) font.setUnderline(f.fontUnderline()) item.setFont(0, font) # update looks of default styles for name in textformats.defaultStyles: setItemTextFormat(self.defaultStyles[name], data.defaultStyles[name]) # update looks of all the specific styles for group, styles in ly.colorize.default_mapping(): children = self.allStyles[group][1] for name, inherit, clss in styles: f = QTextCharFormat(data.defaultStyles[inherit] ) if inherit else QTextCharFormat() f.merge(data.allStyles[group][name]) setItemTextFormat(children[name], f) def baseColorsChanged(self, name): # keep data up to date with base colors data = self.data[self.scheme.currentScheme()] data.baseColors[name] = self.baseColorsWidget.color[name].color() self.updateDisplay() self.changed.emit() def customAttributesChanged(self): item = self.tree.currentItem() if not item or not item.parent(): return data = self.data[self.scheme.currentScheme()] if item.parent() is self.defaultStylesItem: # a default style has been changed data.defaultStyles[ item.name] = self.customAttributesWidget.textFormat() else: # a specific style has been changed group, name = item.parent().group, item.name data.allStyles[group][ name] = self.customAttributesWidget.textFormat() self.updateDisplay() self.changed.emit() def import_(self, filename): from . import import_export import_export.importTheme(filename, self, self.scheme) def export(self, name, filename): from . import import_export try: import_export.exportTheme(self, name, filename) except (IOError, OSError) as e: QMessageBox.critical( self, _("Error"), _("Can't write to destination:\n\n{url}\n\n{error}").format( url=filename, error=e.strerror)) def loadSettings(self): self.data = {} # holds all data with scheme as key self._printScheme = QSettings().value("printer_scheme", "default", str) self.scheme.loadSettings("editor_scheme", "editor_schemes") def saveSettings(self): self.scheme.saveSettings("editor_scheme", "editor_schemes", "fontscolors") for scheme in self.scheme.schemes(): if scheme in self.data: self.data[scheme].save(scheme) if self._printScheme: QSettings().setValue("printer_scheme", self._printScheme) else: QSettings().remove("printer_scheme")
class Browser(preferences.Group): def __init__(self, page): super(Browser, self).__init__(page) layout = QGridLayout() self.setLayout(layout) self.languagesLabel = QLabel() self.languages = QComboBox(currentIndexChanged=self.changed) layout.addWidget(self.languagesLabel, 0, 0) layout.addWidget(self.languages, 0, 1) items = ['', ''] items.extend( language_names.languageName(l, l) for l in lilydoc.translations) self.languages.addItems(items) self.fontLabel = QLabel() self.fontChooser = QFontComboBox(currentFontChanged=self.changed) self.fontSize = QSpinBox(valueChanged=self.changed) self.fontSize.setRange(6, 32) self.fontSize.setSingleStep(1) layout.addWidget(self.fontLabel, 1, 0) layout.addWidget(self.fontChooser, 1, 1) layout.addWidget(self.fontSize, 1, 2) app.translateUI(self) def translateUI(self): self.setTitle(_("Documentation Browser")) self.languagesLabel.setText(_("Preferred Language:")) self.languages.setItemText(0, _("Default")) self.languages.setItemText(1, _("English (untranslated)")) self.fontLabel.setText(_("Font:")) def loadSettings(self): s = QSettings() s.beginGroup("documentation") lang = s.value("language", "default", str) if lang in lilydoc.translations: i = lilydoc.translations.index(lang) + 2 elif lang == "C": i = 1 else: i = 0 self.languages.setCurrentIndex(i) font = self.font() family = s.value("fontfamily", "", str) if family: font.setFamily(family) size = s.value("fontsize", 16, int) with qutil.signalsBlocked(self.fontChooser, self.fontSize): self.fontChooser.setCurrentFont(font) self.fontSize.setValue(size) def saveSettings(self): s = QSettings() s.beginGroup("documentation") langs = ['default', 'C'] + lilydoc.translations s.setValue("language", langs[self.languages.currentIndex()]) s.setValue("fontfamily", self.fontChooser.currentFont().family()) s.setValue("fontsize", self.fontSize.value())
class GuiConfigEditEditor(QWidget): def __init__(self, theParent): QWidget.__init__(self, theParent) self.mainConf = nw.CONFIG self.theParent = theParent self.outerBox = QGridLayout() # Text Style self.textStyle = QGroupBox("Text Style", self) self.textStyleForm = QGridLayout(self) self.textStyle.setLayout(self.textStyleForm) self.textStyleFont = QFontComboBox() self.textStyleFont.setMaximumWidth(250) self.textStyleFont.setCurrentFont(QFont(self.mainConf.textFont)) self.textStyleSize = QSpinBox(self) self.textStyleSize.setMinimum(5) self.textStyleSize.setMaximum(120) self.textStyleSize.setSingleStep(1) self.textStyleSize.setValue(self.mainConf.textSize) self.textStyleForm.addWidget(QLabel("Font Family"), 0, 0) self.textStyleForm.addWidget(self.textStyleFont, 0, 1) self.textStyleForm.addWidget(QLabel("Size"), 0, 2) self.textStyleForm.addWidget(self.textStyleSize, 0, 3) self.textStyleForm.setColumnStretch(4, 1) # Text Flow self.textFlow = QGroupBox("Text Flow", self) self.textFlowForm = QGridLayout(self) self.textFlow.setLayout(self.textFlowForm) self.textFlowFixed = QCheckBox(self) self.textFlowFixed.setToolTip( "Make text in editor fixed width and scale margins instead.") if self.mainConf.textFixedW: self.textFlowFixed.setCheckState(Qt.Checked) else: self.textFlowFixed.setCheckState(Qt.Unchecked) self.textFlowWidth = QSpinBox(self) self.textFlowWidth.setMinimum(300) self.textFlowWidth.setMaximum(10000) self.textFlowWidth.setSingleStep(10) self.textFlowWidth.setValue(self.mainConf.textWidth) self.textFlowJustify = QCheckBox(self) self.textFlowJustify.setToolTip( "Justify text in main document editor.") if self.mainConf.doJustify: self.textFlowJustify.setCheckState(Qt.Checked) else: self.textFlowJustify.setCheckState(Qt.Unchecked) self.textFlowForm.addWidget(QLabel("Fixed Width"), 0, 0) self.textFlowForm.addWidget(self.textFlowFixed, 0, 1) self.textFlowForm.addWidget(self.textFlowWidth, 0, 2) self.textFlowForm.addWidget(QLabel("px"), 0, 3) self.textFlowForm.addWidget(QLabel("Justify Text"), 1, 0) self.textFlowForm.addWidget(self.textFlowJustify, 1, 1) self.textFlowForm.setColumnStretch(4, 1) # Text Margins self.textMargin = QGroupBox("Margins", self) self.textMarginForm = QGridLayout(self) self.textMargin.setLayout(self.textMarginForm) self.textMarginDoc = QSpinBox(self) self.textMarginDoc.setMinimum(0) self.textMarginDoc.setMaximum(2000) self.textMarginDoc.setSingleStep(1) self.textMarginDoc.setValue(self.mainConf.textMargin) self.textMarginTab = QSpinBox(self) self.textMarginTab.setMinimum(0) self.textMarginTab.setMaximum(200) self.textMarginTab.setSingleStep(1) self.textMarginTab.setValue(self.mainConf.tabWidth) self.textMarginForm.addWidget(QLabel("Document"), 0, 0) self.textMarginForm.addWidget(self.textMarginDoc, 0, 1) self.textMarginForm.addWidget(QLabel("px"), 0, 2) self.textMarginForm.addWidget(QLabel("Tab Width"), 2, 0) self.textMarginForm.addWidget(self.textMarginTab, 2, 1) self.textMarginForm.addWidget(QLabel("px"), 2, 2) self.textMarginForm.setColumnStretch(4, 1) # Automatic Features self.autoReplace = QGroupBox("Automatic Features", self) self.autoReplaceForm = QGridLayout(self) self.autoReplace.setLayout(self.autoReplaceForm) self.autoSelect = QCheckBox(self) self.autoSelect.setToolTip( "Auto-select word under cursor when applying formatting.") if self.mainConf.autoSelect: self.autoSelect.setCheckState(Qt.Checked) else: self.autoSelect.setCheckState(Qt.Unchecked) self.autoReplaceMain = QCheckBox(self) self.autoReplaceMain.setToolTip("Auto-replace text as you type.") if self.mainConf.doReplace: self.autoReplaceMain.setCheckState(Qt.Checked) else: self.autoReplaceMain.setCheckState(Qt.Unchecked) self.autoReplaceSQ = QCheckBox(self) self.autoReplaceSQ.setToolTip("Auto-replace single quotes.") if self.mainConf.doReplaceSQuote: self.autoReplaceSQ.setCheckState(Qt.Checked) else: self.autoReplaceSQ.setCheckState(Qt.Unchecked) self.autoReplaceDQ = QCheckBox(self) self.autoReplaceDQ.setToolTip("Auto-replace double quotes.") if self.mainConf.doReplaceDQuote: self.autoReplaceDQ.setCheckState(Qt.Checked) else: self.autoReplaceDQ.setCheckState(Qt.Unchecked) self.autoReplaceDash = QCheckBox(self) self.autoReplaceDash.setToolTip( "Auto-replace double and triple hyphens with short and long dash.") if self.mainConf.doReplaceDash: self.autoReplaceDash.setCheckState(Qt.Checked) else: self.autoReplaceDash.setCheckState(Qt.Unchecked) self.autoReplaceDots = QCheckBox(self) self.autoReplaceDots.setToolTip( "Auto-replace three dots with ellipsis.") if self.mainConf.doReplaceDots: self.autoReplaceDots.setCheckState(Qt.Checked) else: self.autoReplaceDots.setCheckState(Qt.Unchecked) self.autoReplaceForm.addWidget(QLabel("Auto-Select Text"), 0, 0) self.autoReplaceForm.addWidget(self.autoSelect, 0, 1) self.autoReplaceForm.addWidget(QLabel("Auto-Replace:"), 1, 0) self.autoReplaceForm.addWidget(self.autoReplaceMain, 1, 1) self.autoReplaceForm.addWidget(QLabel("\u2192 Single Quotes"), 2, 0) self.autoReplaceForm.addWidget(self.autoReplaceSQ, 2, 1) self.autoReplaceForm.addWidget(QLabel("\u2192 Double Quotes"), 3, 0) self.autoReplaceForm.addWidget(self.autoReplaceDQ, 3, 1) self.autoReplaceForm.addWidget(QLabel("\u2192 Hyphens with Dash"), 4, 0) self.autoReplaceForm.addWidget(self.autoReplaceDash, 4, 1) self.autoReplaceForm.addWidget(QLabel("\u2192 Dots with Ellipsis"), 5, 0) self.autoReplaceForm.addWidget(self.autoReplaceDots, 5, 1) self.autoReplaceForm.setColumnStretch(2, 1) # Quote Style self.quoteStyle = QGroupBox("Quotation Style", self) self.quoteStyleForm = QGridLayout(self) self.quoteStyle.setLayout(self.quoteStyleForm) self.quoteSingleStyleO = QLineEdit() self.quoteSingleStyleO.setMaxLength(1) self.quoteSingleStyleO.setFixedWidth(30) self.quoteSingleStyleO.setAlignment(Qt.AlignCenter) self.quoteSingleStyleO.setText(self.mainConf.fmtSingleQuotes[0]) self.quoteSingleStyleC = QLineEdit() self.quoteSingleStyleC.setMaxLength(1) self.quoteSingleStyleC.setFixedWidth(30) self.quoteSingleStyleC.setAlignment(Qt.AlignCenter) self.quoteSingleStyleC.setText(self.mainConf.fmtSingleQuotes[1]) self.quoteDoubleStyleO = QLineEdit() self.quoteDoubleStyleO.setMaxLength(1) self.quoteDoubleStyleO.setFixedWidth(30) self.quoteDoubleStyleO.setAlignment(Qt.AlignCenter) self.quoteDoubleStyleO.setText(self.mainConf.fmtDoubleQuotes[0]) self.quoteDoubleStyleC = QLineEdit() self.quoteDoubleStyleC.setMaxLength(1) self.quoteDoubleStyleC.setFixedWidth(30) self.quoteDoubleStyleC.setAlignment(Qt.AlignCenter) self.quoteDoubleStyleC.setText(self.mainConf.fmtDoubleQuotes[1]) self.quoteStyleForm.addWidget(QLabel("Single Quotes"), 0, 0, 1, 3) self.quoteStyleForm.addWidget(QLabel("Open"), 1, 0) self.quoteStyleForm.addWidget(self.quoteSingleStyleO, 1, 1) self.quoteStyleForm.addWidget(QLabel("Close"), 1, 2) self.quoteStyleForm.addWidget(self.quoteSingleStyleC, 1, 3) self.quoteStyleForm.addWidget(QLabel("Double Quotes"), 2, 0, 1, 3) self.quoteStyleForm.addWidget(QLabel("Open"), 3, 0) self.quoteStyleForm.addWidget(self.quoteDoubleStyleO, 3, 1) self.quoteStyleForm.addWidget(QLabel("Close"), 3, 2) self.quoteStyleForm.addWidget(self.quoteDoubleStyleC, 3, 3) self.quoteStyleForm.setColumnStretch(4, 1) self.quoteStyleForm.setRowStretch(4, 1) # Assemble self.outerBox.addWidget(self.textStyle, 0, 0, 1, 2) self.outerBox.addWidget(self.textFlow, 1, 0) self.outerBox.addWidget(self.textMargin, 1, 1) self.outerBox.addWidget(self.autoReplace, 2, 0) self.outerBox.addWidget(self.quoteStyle, 2, 1) self.outerBox.setColumnStretch(2, 1) self.setLayout(self.outerBox) return def saveValues(self): validEntries = True textFont = self.textStyleFont.currentFont().family() textSize = self.textStyleSize.value() self.mainConf.textFont = textFont self.mainConf.textSize = textSize textWidth = self.textFlowWidth.value() textFixedW = self.textFlowFixed.isChecked() doJustify = self.textFlowJustify.isChecked() self.mainConf.textWidth = textWidth self.mainConf.textFixedW = textFixedW self.mainConf.doJustify = doJustify textMargin = self.textMarginDoc.value() tabWidth = self.textMarginTab.value() self.mainConf.textMargin = textMargin self.mainConf.tabWidth = tabWidth autoSelect = self.autoSelect.isChecked() doReplace = self.autoReplaceMain.isChecked() doReplaceSQuote = self.autoReplaceSQ.isChecked() doReplaceDQuote = self.autoReplaceDQ.isChecked() doReplaceDash = self.autoReplaceDash.isChecked() doReplaceDots = self.autoReplaceDash.isChecked() self.mainConf.autoSelect = autoSelect self.mainConf.doReplace = doReplace self.mainConf.doReplaceSQuote = doReplaceSQuote self.mainConf.doReplaceDQuote = doReplaceDQuote self.mainConf.doReplaceDash = doReplaceDash self.mainConf.doReplaceDots = doReplaceDots fmtSingleQuotesO = self.quoteSingleStyleO.text() fmtSingleQuotesC = self.quoteSingleStyleC.text() fmtDoubleQuotesO = self.quoteDoubleStyleO.text() fmtDoubleQuotesC = self.quoteDoubleStyleC.text() if self._checkQuoteSymbol(fmtSingleQuotesO): self.mainConf.fmtSingleQuotes[0] = fmtSingleQuotesO else: self.theParent.makeAlert( "Invalid quote symbol: %s" % fmtSingleQuotesO, nwAlert.ERROR) validEntries = False if self._checkQuoteSymbol(fmtSingleQuotesC): self.mainConf.fmtSingleQuotes[1] = fmtSingleQuotesC else: self.theParent.makeAlert( "Invalid quote symbol: %s" % fmtSingleQuotesC, nwAlert.ERROR) validEntries = False if self._checkQuoteSymbol(fmtDoubleQuotesO): self.mainConf.fmtDoubleQuotes[0] = fmtDoubleQuotesO else: self.theParent.makeAlert( "Invalid quote symbol: %s" % fmtDoubleQuotesO, nwAlert.ERROR) validEntries = False if self._checkQuoteSymbol(fmtDoubleQuotesC): self.mainConf.fmtDoubleQuotes[1] = fmtDoubleQuotesC else: self.theParent.makeAlert( "Invalid quote symbol: %s" % fmtDoubleQuotesC, nwAlert.ERROR) validEntries = False self.mainConf.confChanged = True return validEntries, False ## # Internal Functions ## def _checkQuoteSymbol(self, toCheck): if len(toCheck) != 1: return False if toCheck in nwQuotes.SYMBOLS: return True return False
class GlobalFontDialog(widgets.dialog.Dialog): def __init__(self, parent=None): super(GlobalFontDialog, self).__init__(parent) self._messageLabel.setWordWrap(True) layout = QGridLayout() layout.setContentsMargins(0, 0, 0, 0) self.mainWidget().setLayout(layout) self.romanLabel = QLabel() self.romanCombo = QFontComboBox() self.sansLabel = QLabel() self.sansCombo = QFontComboBox() self.typewriterLabel = QLabel() self.typewriterCombo = QFontComboBox( fontFilters=QFontComboBox.MonospacedFonts) layout.addWidget(self.romanLabel, 0, 0) layout.addWidget(self.romanCombo, 0, 1, 1, 2) layout.addWidget(self.sansLabel, 1, 0) layout.addWidget(self.sansCombo, 1, 1, 1, 2) layout.addWidget(self.typewriterLabel, 2, 0) layout.addWidget(self.typewriterCombo, 2, 1, 1, 2) self.loadSettings() self.finished.connect(self.saveSettings) app.translateUI(self) def translateUI(self): self.setWindowTitle(app.caption(_("Global Fonts"))) self.setMessage( _("Please select the three global fonts to use for " r"<code>\roman</code>, <code>\sans</code>, and <code>\typewriter</code> " "respectively.")) self.romanLabel.setText(_("Roman Font:")) self.sansLabel.setText(_("Sans Font:")) self.typewriterLabel.setText(_("Typewriter Font:")) def romanFont(self): return self.romanCombo.currentFont().family() def setromanFont(self, family): self.romanCombo.setCurrentFont(QFont(family)) def sansFont(self): return self.sansCombo.currentFont().family() def setSansFont(self, family): self.sansCombo.setCurrentFont(QFont(family)) def typewriterFont(self): return self.typewriterCombo.currentFont().family() def settypewriterFont(self, family): self.typewriterCombo.setCurrentFont(QFont(family)) def loadSettings(self): s = QSettings() s.beginGroup("global_font_dialog") roman = s.value("roman", "Century Schoolbook L", str) self.romanCombo.setCurrentFont(QFont(roman)) sans = s.value("sans", "sans-serif", str) self.sansCombo.setCurrentFont(QFont(sans)) typewriter = s.value("typewriter", "monospace", str) self.typewriterCombo.setCurrentFont(QFont(typewriter)) def saveSettings(self): s = QSettings() s.beginGroup("global_font_dialog") s.setValue("roman", self.romanCombo.currentFont().family()) s.setValue("sans", self.sansCombo.currentFont().family()) s.setValue("typewriter", self.typewriterCombo.currentFont().family())
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() centralWidget = QWidget() fontLabel = QLabel("Font:") self.fontCombo = QFontComboBox() sizeLabel = QLabel("Size:") self.sizeCombo = QComboBox() styleLabel = QLabel("Style:") self.styleCombo = QComboBox() fontMergingLabel = QLabel("Automatic Font Merging:") self.fontMerging = QCheckBox() self.fontMerging.setChecked(True) self.scrollArea = QScrollArea() self.characterWidget = CharacterWidget() self.scrollArea.setWidget(self.characterWidget) self.findStyles(self.fontCombo.currentFont()) self.findSizes(self.fontCombo.currentFont()) self.lineEdit = QLineEdit() clipboardButton = QPushButton("&To clipboard") self.clipboard = QApplication.clipboard() self.fontCombo.currentFontChanged.connect(self.findStyles) self.fontCombo.activated[str].connect(self.characterWidget.updateFont) self.styleCombo.activated[str].connect( self.characterWidget.updateStyle) self.sizeCombo.currentIndexChanged[str].connect( self.characterWidget.updateSize) self.characterWidget.characterSelected.connect(self.insertCharacter) clipboardButton.clicked.connect(self.updateClipboard) controlsLayout = QHBoxLayout() controlsLayout.addWidget(fontLabel) controlsLayout.addWidget(self.fontCombo, 1) controlsLayout.addWidget(sizeLabel) controlsLayout.addWidget(self.sizeCombo, 1) controlsLayout.addWidget(styleLabel) controlsLayout.addWidget(self.styleCombo, 1) controlsLayout.addWidget(fontMergingLabel) controlsLayout.addWidget(self.fontMerging, 1) controlsLayout.addStretch(1) lineLayout = QHBoxLayout() lineLayout.addWidget(self.lineEdit, 1) lineLayout.addSpacing(12) lineLayout.addWidget(clipboardButton) centralLayout = QVBoxLayout() centralLayout.addLayout(controlsLayout) centralLayout.addWidget(self.scrollArea, 1) centralLayout.addSpacing(4) centralLayout.addLayout(lineLayout) centralWidget.setLayout(centralLayout) self.setCentralWidget(centralWidget) self.setWindowTitle("Character Map") def findStyles(self, font): fontDatabase = QFontDatabase() currentItem = self.styleCombo.currentText() self.styleCombo.clear() for style in fontDatabase.styles(font.family()): self.styleCombo.addItem(style) styleIndex = self.styleCombo.findText(currentItem) if styleIndex == -1: self.styleCombo.setCurrentIndex(0) else: self.styleCombo.setCurrentIndex(styleIndex) def findSizes(self, font): fontDatabase = QFontDatabase() currentSize = self.sizeCombo.currentText() self.sizeCombo.blockSignals(True) self.sizeCombo.clear() if fontDatabase.isSmoothlyScalable(font.family(), fontDatabase.styleString(font)): for size in QFontDatabase.standardSizes(): self.sizeCombo.addItem(str(size)) self.sizeCombo.setEditable(True) else: for size in fontDatabase.smoothSizes( font.family(), fontDatabase.styleString(font)): self.sizeCombo.addItem(str(size)) self.sizeCombo.setEditable(False) self.sizeCombo.blockSignals(False) sizeIndex = self.sizeCombo.findText(currentSize) if sizeIndex == -1: self.sizeCombo.setCurrentIndex(max(0, self.sizeCombo.count() / 3)) else: self.sizeCombo.setCurrentIndex(sizeIndex) def insertCharacter(self, character): self.lineEdit.insert(character) def updateClipboard(self): self.clipboard.setText(self.lineEdit.text(), QClipboard.Clipboard) self.clipboard.setText(self.lineEdit.text(), QClipboard.Selection)
class RSBGDocker(DockWidget): def __init__(self): super().__init__() self.setWindowTitle("Rogudator's speech bubble generator") mainLayout = QVBoxLayout() self.addOnPage = QPushButton("Add on Page") mainLayout.addWidget(self.addOnPage) previewLabel = QLabel("Preview") mainLayout.addWidget(previewLabel) self.preview = QSvgWidget(self) self.preview.setMinimumHeight(200) #self.preview.setAspectRatioMode(Qt.AspectRatioMode.KeepAspectRatio) mainLayout.addWidget(self.preview) bubbleTypes = QGroupBox() bubbleTypes.setTitle("Bubble type") bubbleTypesLayout = QHBoxLayout() self.squareBubble = QRadioButton(self) self.squareBubble.setText("Square") bubbleTypesLayout.addWidget(self.squareBubble) self.roundBubble = QRadioButton(self) self.roundBubble.setText("Round") self.roundBubble.setChecked(True) bubbleTypesLayout.addWidget(self.roundBubble) bubbleTypes.setLayout(bubbleTypesLayout) self.bubbleColorButton = QPushButton(self) self.bubbleColor = QColor("white") bubbleColorImage = QPixmap(32, 32) bubbleColorImage.fill(self.bubbleColor) bubbleColorIcon = QIcon(bubbleColorImage) self.bubbleColorButton.setIcon(bubbleColorIcon) self.bubbleColorButton.setFixedWidth(self.bubbleColorButton.height()) bubbleTypesLayout.addWidget(self.bubbleColorButton) mainLayout.addWidget(bubbleTypes) outlineSize = QGroupBox("Outline") outlineSliderAndSpinBox = QHBoxLayout() self.outlineSlider = QSlider(self) self.outlineSlider.setMinimum(0) self.outlineSlider.setMaximum(10) self.outlineSlider.setValue(3) self.outlineSlider.setOrientation(Qt.Orientation.Horizontal) outlineSliderAndSpinBox.addWidget(self.outlineSlider) self.outlineSpinBox = QSpinBox(self) self.outlineSpinBox.setMinimum(0) self.outlineSpinBox.setValue(3) outlineSliderAndSpinBox.addWidget(self.outlineSpinBox) self.outlineColorButton = QPushButton(self) self.outlineColor = QColor("black") outlineColorImage = QPixmap(32, 32) outlineColorImage.fill(self.outlineColor) outlineColorIcon = QIcon(outlineColorImage) self.outlineColorButton.setIcon(outlineColorIcon) self.outlineColorButton.setFixedWidth(self.outlineColorButton.height()) outlineSliderAndSpinBox.addWidget(self.outlineColorButton) outlineSize.setLayout(outlineSliderAndSpinBox) mainLayout.addWidget(outlineSize) speechGroup = QGroupBox("Speech") speechGroupLayout = QVBoxLayout() fontRow = QHBoxLayout() self.speechFont = QFontComboBox(self) fontRow.addWidget(self.speechFont) self.speechFontSize = QSpinBox(self) self.speechFontSize.setValue(14) self.speechFontSize.setMinimum(1) fontRow.addWidget(self.speechFontSize) self.currentFontColorButton = QPushButton(self) self.speechFontColor = QColor("black") fontColorImage = QPixmap(32, 32) fontColorImage.fill(self.speechFontColor) fontColorIcon = QIcon(fontColorImage) self.currentFontColorButton.setIcon(fontColorIcon) self.currentFontColorButton.setFixedWidth( self.currentFontColorButton.height()) fontRow.addWidget(self.currentFontColorButton) speechGroupLayout.addLayout(fontRow) self.bubbleText = QTextEdit("Rogudator's speech bubble generator!") speechGroupLayout.addWidget(self.bubbleText) self.autocenter = QCheckBox(self) self.autocenter.setText("Center automatically") self.autocenter.setChecked(True) speechGroupLayout.addWidget(self.autocenter) self.averageLineLength = QGroupBox() averageLineLengthSliderAndSpinBox = QHBoxLayout() self.averageLineLengthSlider = QSlider(self) self.averageLineLengthSlider.setMinimum(0) self.averageLineLengthSlider.setMaximum(100) self.averageLineLengthSlider.setOrientation(Qt.Orientation.Horizontal) averageLineLengthSliderAndSpinBox.addWidget( self.averageLineLengthSlider) self.averageLineLengthSpinBox = QSpinBox(self) self.averageLineLengthSpinBox.setMinimum(0) averageLineLengthSliderAndSpinBox.addWidget( self.averageLineLengthSpinBox) self.averageLineLength.setLayout(averageLineLengthSliderAndSpinBox) self.averageLineLength.setDisabled(True) speechGroupLayout.addWidget(self.averageLineLength) speechGroup.setLayout(speechGroupLayout) mainLayout.addWidget(speechGroup) tailSize = QGroupBox() tailSize.setTitle("Tail size") tailSliderAndSpinBox = QHBoxLayout() self.tailSlider = QSlider(self) self.tailSlider.setMinimum(0) self.tailSlider.setMaximum(self.speechFontSize.value() * 10) self.tailSlider.setOrientation(Qt.Orientation.Horizontal) tailSliderAndSpinBox.addWidget(self.tailSlider) self.tailSpinBox = QSpinBox(self) self.tailSpinBox.setMinimum(0) self.tailSpinBox.setMaximum(self.speechFontSize.value() * 10) tailSliderAndSpinBox.addWidget(self.tailSpinBox) tailSize.setLayout(tailSliderAndSpinBox) mainLayout.addWidget(tailSize) self.tailPositions = QGroupBox() self.tailPositions.setTitle("Tail position") tailPositionsLayout = QHBoxLayout() self.tailPosition = [] for i in range(8): self.tailPosition.append(QRadioButton(self)) self.tailPosition[i].setText(str(i + 1)) self.tailPosition[i].clicked.connect(self.updatePreview) tailPositionsLayout.addWidget(self.tailPosition[i]) self.tailPositions.setLayout(tailPositionsLayout) self.tailPositions.setDisabled(True) mainLayout.addWidget(self.tailPositions) self.updatePreview() self.addOnPage.clicked.connect(self.addOnPageShape) self.squareBubble.clicked.connect(self.updatePreview) self.roundBubble.clicked.connect(self.updatePreview) self.bubbleColorButton.clicked.connect(self.changeBubbleColor) self.outlineSlider.valueChanged.connect(self.outlineSpinBoxUpdate) self.outlineSpinBox.valueChanged.connect(self.outlineSliderUpdate) self.outlineSpinBox.valueChanged.connect(self.updatePreview) self.outlineColorButton.clicked.connect(self.changeOutlineColor) self.bubbleText.textChanged.connect(self.updatePreview) self.speechFontSize.valueChanged.connect(self.updatePreview) self.speechFontSize.valueChanged.connect(self.tailSliderUpdateMaximum) self.currentFontColorButton.clicked.connect(self.changeFontColor) self.speechFont.currentFontChanged.connect(self.updatePreview) self.autocenter.stateChanged.connect(self.enableAverageLineLength) self.autocenter.clicked.connect(self.updatePreview) self.averageLineLengthSlider.valueChanged.connect( self.averageLineLengthSpinBoxUpdate) self.averageLineLengthSpinBox.valueChanged.connect(self.updatePreview) self.averageLineLengthSpinBox.valueChanged.connect( self.averageLineLengthSliderUpdate) self.tailSlider.valueChanged.connect(self.tailSpinBoxUpdate) self.tailSpinBox.valueChanged.connect(self.tailSliderUpdate) self.tailSpinBox.valueChanged.connect(self.updatePreview) self.scrollMainLayout = QScrollArea(self) self.scrollMainLayout.setWidgetResizable(True) self.scrollMainLayout.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) widget = QWidget() widget.setLayout(mainLayout) self.scrollMainLayout.setWidget(widget) self.setWidget(self.scrollMainLayout) self.show() def tailSliderUpdateMaximum(self): self.tailSlider.setMaximum(self.speechFontSize.value() * 10) self.tailSpinBox.setMaximum(self.speechFontSize.value() * 10) def changeBubbleColor(self): self.bubbleColor = QColorDialog.getColor(self.bubbleColor) colorImage = QPixmap(32, 32) colorImage.fill(self.bubbleColor) colorIcon = QIcon(colorImage) self.bubbleColorButton.setIcon(colorIcon) self.updatePreview() def changeFontColor(self): self.speechFontColor = QColorDialog.getColor(self.speechFontColor) colorImage = QPixmap(32, 32) colorImage.fill(self.speechFontColor) colorIcon = QIcon(colorImage) self.currentFontColorButton.setIcon(colorIcon) self.updatePreview() def changeOutlineColor(self): self.outlineColor = QColorDialog.getColor(self.outlineColor) colorImage = QPixmap(32, 32) colorImage.fill(self.outlineColor) colorIcon = QIcon(colorImage) self.outlineColorButton.setIcon(colorIcon) self.updatePreview() def outlineSpinBoxUpdate(self): self.outlineSpinBox.setValue(self.outlineSlider.value()) def outlineSliderUpdate(self): if self.outlineSpinBox.value() < 51: self.outlineSlider.setValue(self.outlineSpinBox.value()) def tailSpinBoxUpdate(self): self.tailSpinBox.setValue(self.tailSlider.value()) if self.tailSlider.value() == 0: self.tailPositions.setDisabled(True) else: self.tailPositions.setDisabled(False) def tailSliderUpdate(self): if self.tailSpinBox.value() < 101: self.tailSlider.setValue(self.tailSpinBox.value()) def enableAverageLineLength(self): if self.autocenter.isChecked(): self.averageLineLength.setDisabled(True) else: self.averageLineLength.setDisabled(False) def averageLineLengthSpinBoxUpdate(self): self.averageLineLengthSpinBox.setValue( self.averageLineLengthSlider.value()) def averageLineLengthSliderUpdate(self): if self.averageLineLengthSpinBox.value() < 101: self.averageLineLengthSlider.setValue( self.averageLineLengthSpinBox.value()) def getSpeechLines(self, text, lineLength): size = 0 speach = "" lines = [] if (lineLength > 0): words = text.split(" ") for word in words: speach += word size += len(word) if size < lineLength: speach += " " else: size = 0 lines.append(speach) speach = "" if (speach != "") and (speach != " "): lines.append(speach.strip()) else: lines = text.split("\n") return lines def getPreview(self): lineLength = int((pow( (len(self.bubbleText.toPlainText())), 1 / 2)) * 1.8) if not (self.autocenter.isChecked()): lineLength = self.averageLineLengthSpinBox.value() lines = self.getSpeechLines(self.bubbleText.toPlainText(), lineLength) biggestLine = "" for line in lines: if (len(line) > len(biggestLine)): biggestLine = line #Calculate text box size font = self.speechFont.currentFont() font.setPixelSize(int(self.speechFontSize.value() * 1.3)) fontSize = self.speechFontSize.value() textHeight = int(fontSize * (len(lines)) - (fontSize - QFontMetrics(font).capHeight())) textWidth = QFontMetrics(font).width(biggestLine) tailLength = self.tailSpinBox.value() framePadding = fontSize tailPadding = tailLength bubblePadding = int(fontSize * 1.5) textTag = "<text x=\"{}\" y=\"{}\" style=\"font-size:{};font-family:{};fill:{};text-anchor:middle\" >{}</text>" text = "" textStartX = framePadding + tailPadding + bubblePadding + (int( textWidth / 2)) textStartY = framePadding + tailPadding + bubblePadding + QFontMetrics( font).capHeight() for line in lines: text += textTag.format(textStartX, textStartY, fontSize, font.family(), self.speechFontColor.name(), line) textStartY += fontSize bubbleCoordinatesX0 = framePadding + tailPadding bubbleCoordinatesY0 = framePadding + tailPadding bubbleCoordinatesXHalf = framePadding + tailPadding + bubblePadding + ( int(textWidth / 2)) bubbleCoordinatesYHalf = framePadding + tailPadding + bubblePadding + ( int(textHeight / 2)) bubbleCoordinatesX = framePadding + tailPadding + bubblePadding + textWidth + bubblePadding bubbleCoordinatesY = framePadding + tailPadding + bubblePadding + textHeight + bubblePadding bubbleCoordinates = [] bubbleCoordinates.append( BubbleCoordinates(bubbleCoordinatesXHalf, bubbleCoordinatesY0)) bubbleCoordinates.append( BubbleCoordinates(bubbleCoordinatesX, bubbleCoordinatesY0)) bubbleCoordinates.append( BubbleCoordinates(bubbleCoordinatesX, bubbleCoordinatesYHalf)) bubbleCoordinates.append( BubbleCoordinates(bubbleCoordinatesX, bubbleCoordinatesY)) bubbleCoordinates.append( BubbleCoordinates(bubbleCoordinatesXHalf, bubbleCoordinatesY)) bubbleCoordinates.append( BubbleCoordinates(bubbleCoordinatesX0, bubbleCoordinatesY)) bubbleCoordinates.append( BubbleCoordinates(bubbleCoordinatesX0, bubbleCoordinatesYHalf)) bubbleCoordinates.append( BubbleCoordinates(bubbleCoordinatesX0, bubbleCoordinatesY0)) i = 0 bubbleCoordinatesString = "M" bubbleCoordinatesStringEnd = str(bubbleCoordinates[0].x) + "," + str( bubbleCoordinates[0].y) + "Z" while (i < 8): if (self.roundBubble.isChecked()): if (self.tailSpinBox.value() > 0): #for coordinates in center (even) textWidth01 = int(pow(textWidth, 1 / 2.8)) textHeight01 = int(pow(textHeight, 1 / 2)) #for coordinates in the corner (odd) x04 = int( (bubbleCoordinates[1].x - bubbleCoordinates[0].x) * 0.4) x06 = int( (bubbleCoordinates[1].x - bubbleCoordinates[0].x) * 0.6) y04 = int( (bubbleCoordinates[2].y - bubbleCoordinates[1].y) * 0.4) y06 = int( (bubbleCoordinates[2].y - bubbleCoordinates[1].y) * 0.6) if i == 0 and self.tailPosition[i].isChecked(): bubbleCoordinatesString += str( bubbleCoordinates[0].x - textWidth01) + "," + str( bubbleCoordinates[0].y) + " L" + str( bubbleCoordinates[0].x) + "," + str( bubbleCoordinates[0].y - tailLength) + " " + str( bubbleCoordinates[0].x + textWidth01) + "," + str( bubbleCoordinates[0].y) + " " bubbleCoordinatesStringEnd = str( bubbleCoordinates[0].x - textWidth01) + "," + str( bubbleCoordinates[0].y) + "Z" elif i == 2 and self.tailPosition[i].isChecked(): bubbleCoordinatesString += str( bubbleCoordinates[2].x) + "," + str( bubbleCoordinates[2].y - textHeight01) + " L" + str( bubbleCoordinates[2].x + tailLength) + "," + str( bubbleCoordinates[2].y) + " " + str( bubbleCoordinates[2].x ) + "," + str(bubbleCoordinates[2].y + textHeight01) + " " elif i == 4 and self.tailPosition[i].isChecked(): bubbleCoordinatesString += str( bubbleCoordinates[4].x + textWidth01) + "," + str( bubbleCoordinates[4].y) + " L" + str( bubbleCoordinates[4].x) + "," + str( bubbleCoordinates[4].y + tailLength) + " " + str( bubbleCoordinates[4].x - textWidth01) + "," + str( bubbleCoordinates[4].y) + " " elif i == 6 and self.tailPosition[i].isChecked(): bubbleCoordinatesString += str( bubbleCoordinates[6].x) + "," + str( bubbleCoordinates[6].y + textHeight01) + " L" + str( bubbleCoordinates[6].x - tailLength) + "," + str( bubbleCoordinates[6].y) + " " + str( bubbleCoordinates[6].x ) + "," + str(bubbleCoordinates[6].y - textHeight01) + " " elif i == 1 and self.tailPosition[i].isChecked(): bubbleCoordinatesString += "Q" + str( bubbleCoordinates[1].x - x06 ) + "," + str(bubbleCoordinates[1].y) + " " + str( int((bubbleCoordinates[1].x + bubbleCoordinates[1].x - x06) / 2) ) + "," + str( int((bubbleCoordinates[1].y + y04 + bubbleCoordinates[1].y) / 2)) + " L" + str( bubbleCoordinates[1].x + tailLength ) + "," + str( bubbleCoordinates[1].y - tailLength ) + " " + str( int((bubbleCoordinates[1].x + bubbleCoordinates[1].x - x04) / 2) ) + "," + str( int((bubbleCoordinates[1].y + y06 + bubbleCoordinates[1].y) / 2)) + " Q" + str( bubbleCoordinates[1].x ) + "," + str(bubbleCoordinates[1].y + y06) + " " elif i == 3 and self.tailPosition[i].isChecked(): bubbleCoordinatesString += "Q" + str( bubbleCoordinates[3].x) + "," + str( bubbleCoordinates[3].y - y06) + " " + str( int( (bubbleCoordinates[3].x + bubbleCoordinates[3].x - x04) / 2 )) + "," + str( int((bubbleCoordinates[3].y - y06 + bubbleCoordinates[3].y) / 2) ) + " L" + str( bubbleCoordinates[3].x + tailLength ) + "," + str( bubbleCoordinates[3].y + tailLength ) + " " + str( int((bubbleCoordinates[3].x + bubbleCoordinates[3].x - x06) / 2) ) + "," + str( int((bubbleCoordinates[3].y - y04 + bubbleCoordinates[3].y) / 2)) + " Q" + str( bubbleCoordinates[3].x - x06 ) + "," + str( bubbleCoordinates[3].y) + " " elif i == 5 and self.tailPosition[i].isChecked(): bubbleCoordinatesString += "Q" + str( bubbleCoordinates[5].x + x06 ) + "," + str(bubbleCoordinates[5].y) + " " + str( int((bubbleCoordinates[5].x + bubbleCoordinates[5].x + x06) / 2) ) + "," + str( int((bubbleCoordinates[5].y - y04 + bubbleCoordinates[5].y) / 2)) + " L" + str( bubbleCoordinates[5].x - tailLength ) + "," + str( bubbleCoordinates[5].y + tailLength ) + " " + str( int((bubbleCoordinates[5].x + bubbleCoordinates[5].x + x04) / 2) ) + "," + str( int((bubbleCoordinates[5].y - y06 + bubbleCoordinates[5].y) / 2)) + " Q" + str( bubbleCoordinates[5].x ) + "," + str(bubbleCoordinates[5].y - y06) + " " elif i == 7 and self.tailPosition[i].isChecked(): bubbleCoordinatesString += "Q" + str( bubbleCoordinates[7].x) + "," + str( bubbleCoordinates[7].y + y06) + " " + str( int( (bubbleCoordinates[7].x + bubbleCoordinates[7].x + x04) / 2 )) + "," + str( int((bubbleCoordinates[7].y + y06 + bubbleCoordinates[7].y) / 2) ) + " L" + str( bubbleCoordinates[7].x - tailLength ) + "," + str( bubbleCoordinates[7].y - tailLength ) + " " + str( int((bubbleCoordinates[7].x + bubbleCoordinates[7].x + x06) / 2) ) + "," + str( int((bubbleCoordinates[7].y + y04 + bubbleCoordinates[7].y) / 2)) + " Q" + str( bubbleCoordinates[7].x + x06 ) + "," + str( bubbleCoordinates[7].y) + " " else: if (i % 2 == 0): bubbleCoordinatesString += str( bubbleCoordinates[i].x) + "," + str( bubbleCoordinates[i].y) + " " else: bubbleCoordinatesString += "Q" + str( bubbleCoordinates[i].x) + "," + str( bubbleCoordinates[i].y) + " " else: if (i % 2 == 0): bubbleCoordinatesString += str( bubbleCoordinates[i].x) + "," + str( bubbleCoordinates[i].y) + " " else: bubbleCoordinatesString += "Q" + str( bubbleCoordinates[i].x) + "," + str( bubbleCoordinates[i].y) + " " elif (self.squareBubble.isChecked()): bubbleCoordinatesString += str( bubbleCoordinates[i].x) + "," + str( bubbleCoordinates[i].y) + " " i += 1 bubbleCoordinatesString += bubbleCoordinatesStringEnd pathStyle = "style=\"fill:{};stroke:{};stroke-width:{};stroke-linejoin:round\"".format( self.bubbleColor.name(), self.outlineColor.name(), self.outlineSpinBox.value()) bubble = "<path " + pathStyle + " d=\"" + bubbleCoordinatesString + "\"/>" frameWidth = framePadding + tailPadding + bubblePadding + textWidth + bubblePadding + tailPadding + framePadding frameHeight = framePadding + tailPadding + bubblePadding + textHeight + bubblePadding + tailPadding + framePadding result = "<svg width=\"{}\" height=\"{}\" >{}{}</svg>".format( frameWidth, frameHeight, bubble, text) return result def updatePreview(self): result = self.getPreview() resultBytes = bytearray(result, encoding='utf-8') self.preview.renderer().load(resultBytes) def addOnPageShape(self): result = self.getPreview() d = Krita.instance().activeDocument() root = d.rootNode() l3 = d.createVectorLayer(self.bubbleText.toPlainText()[:16]) root.addChildNode(l3, None) l3.addShapesFromSvg(result) pass def canvasChanged(self, canvas): pass