def _setup_text_editor(self): self.styleComboBox = QComboBox(self.fontToolBar) self.styleComboBox.addItem("Standard") self.styleComboBox.addItem("Bullet List (Disc)") self.styleComboBox.addItem("Bullet List (Circle)") self.styleComboBox.addItem("Bullet List (Square)") self.styleComboBox.addItem("Ordered List (Decimal)") self.styleComboBox.addItem("Ordered List (Alpha lower)") self.styleComboBox.addItem("Ordered List (Alpha upper)") self.styleComboBox.addItem("Ordered List (Roman lower)") self.styleComboBox.addItem("Ordered List (Roman upper)") self.styleComboBox.addItem("Heading 1") self.styleComboBox.addItem("Heading 2") self.styleComboBox.addItem("Heading 3") self.styleComboBox.addItem("Heading 4") self.styleComboBox.addItem("Heading 5") self.styleComboBox.addItem("Heading 6") self.fontToolBar.addWidget(self.styleComboBox) self.fontComboBox = QFontComboBox(self.fontToolBar) # TODO connect self.fontToolBar.addWidget(self.fontComboBox) self.sizeComboBox = QComboBox(self.fontToolBar) # TODO connect sizes = QFontDatabase.standardSizes() [self.sizeComboBox.addItem(str(size)) for size in sizes] self.sizeComboBox.setCurrentIndex( sizes.index(QApplication.font().pointSize())) self.fontToolBar.addWidget(self.sizeComboBox)
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 __init__(self, parent=None): super().__init__(parent) self.setModal(True) self.setWindowTitle('Settings') self.setMinimumWidth(400) self.accepted.connect(self.save) # Editor group self.editor_path_input = QLineEdit() 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('Editor Path:', self.editor_path_input) 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 __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 initUI(self): main_layout = QHBoxLayout() # 第一种信号与槽连接的方法 cb_font = QFontComboBox(currentFontChanged=self.changeLabelFont) cb_font.pyqtConfigure(objectName='fontCombo', editable=False) # 第二种信号与槽连接的方法 cb_font.currentFontChanged.connect(self.changeButtonFont) main_layout.addWidget(cb_font) label = QLabel() label.pyqtConfigure(text='示例文本!', objectName='label') main_layout.addWidget(label) closeButton = QPushButton('关闭') # 第三种连接信号与槽的方法 closeButton.pyqtConfigure(objectName='button', clicked=self.close) main_layout.addWidget(closeButton) vhbox = QVBoxLayout() vhbox.addLayout(main_layout) vhbox.addStretch(1) self.setLayout(vhbox) # 第四种连接信号与槽的方法 QMetaObject.connectSlotsByName(self)
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 __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 __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 makeComboFontStyleBox(self) -> QFontComboBox: """ Create Font Style DropDown """ # ComboBox for font sizes self.combo_font_style = QFontComboBox(self) self.combo_font_style.setToolTip('Change font') self.combo_font_style.setFocusPolicy(Qt.NoFocus) self.combo_font_style.currentFontChanged.connect( self.document.onFontStyleChanged) self.combo_font_style.setCurrentFont(self.document.currentFont()) return self.combo_font_style
def __init__(self, item=None, position=None, scene=None, parent=None): super(QDialog, 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 init_ui(self): # menu bar act_newfile = QAction(QIcon('newfile.png'), '새로운 기사', self) act_newfile.setShortcut('Ctrl+N') act_newfile.setStatusTip('Create New File') act_newfile.triggered.connect(self.new_windows) # todo: link action creating new document act_openfile = QAction(QIcon('openfile.png'), '기사 불러오기', self) act_openfile.setShortcut('Ctrl+O') act_openfile.setStatusTip('Open Existing Article') act_savefile = QAction(QIcon('savefile.png'), '기사 저장하기', self) act_savefile.setShortcut('Ctrl+S') act_savefile.setStatusTip('Save Current Article') act_export = QAction(QIcon('export.png'), '&Export', self) act_export.setShortcut('Ctrl+E') act_export.setStatusTip('Export to Java SourceCode') act_export.triggered.connect(self.export_java) act_import = QAction(QIcon('import.png'), '&Import', self) act_import.setShortcut('Ctrl+I') act_import.setStatusTip('Import lua code') act_import.triggered.connect(self.import_lua) status_bar = self.statusBar() status_bar.showMessage('글자 수 표시 장소') menu_bar = self.menuBar() menu_bar.setNativeMenuBar(False) print(menu_bar.height()) menu_file = menu_bar.addMenu('&File') menu_file.addAction(act_newfile) menu_file.addAction(act_openfile) menu_file.addAction(act_export) menu_file.addAction(act_import) #tool bar fontbox = QFontComboBox(self) fontbox.InsertPolicy() fontbox.setMinimumContentsLength(3) format_bar = self.addToolBar('Format') format_bar.addAction(act_newfile) format_bar.addAction(act_openfile) format_bar.addAction(act_savefile) format_bar.addSeparator() format_bar.addWidget(fontbox)
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 add_font_widgets(self, toolbar: QToolBar): self.combo_Paragraph = QComboBox(toolbar) toolbar.addWidget(self.combo_Paragraph) self.combo_Paragraph.addItem("Paragraph") self.combo_Paragraph.addItem("Bullet List (Disc)") self.combo_Paragraph.addItem("Bullet List (Circle)") self.combo_Paragraph.addItem("Bullet List (Square)") self.combo_Paragraph.addItem("Ordered List (Decimal)") self.combo_Paragraph.addItem("Ordered List (Alpha lower)") self.combo_Paragraph.addItem("Ordered List (Alpha upper)") self.combo_Paragraph.addItem("Ordered List (Roman lower)") self.combo_Paragraph.addItem("Ordered List (Roman upper)") self.combo_Paragraph.activated.connect(self.textStyle) self.combo_Font = QFontComboBox(toolbar) toolbar.addWidget(self.combo_Font) self.combo_Font.activated[str].connect(self.textFamily) self.combo_Font_Size = QComboBox(toolbar) self.combo_Font_Size.setObjectName("combo_Font_Size") toolbar.addWidget(self.combo_Font_Size) self.combo_Font_Size.setEditable(True) db = QFontDatabase() for size in db.standardSizes(): self.combo_Font_Size.addItem(f"{size}") self.combo_Font_Size.activated[str].connect(self.textSize) self.combo_Font_Size.setCurrentIndex( self.combo_Font_Size.findText( f"{QApplication.font().pointSize()}"))
def __init__(self): super(FontSelector, self).__init__() self.frame = QFrame() self.frame.setFrameShape(QFrame.Box) self.frame.setFrameShadow(QFrame.Sunken) self.horizontalLayout = QHBoxLayout(self.frame) self.textBold = QPushButton(self.frame) self.textBold.setMaximumSize(QtCore.QSize(25, 25)) self.textBold.setCheckable(True) self.textBold.setText("B") self.horizontalLayout.addWidget(self.textBold) self.textItalic = QPushButton(self.frame) self.textItalic.setMaximumSize(QtCore.QSize(25, 25)) self.textItalic.setCheckable(True) self.textItalic.setText("I") self.horizontalLayout.addWidget(self.textItalic) self.textUnderline = QPushButton(self.frame) self.textUnderline.setMaximumSize(QtCore.QSize(25, 25)) self.textUnderline.setCheckable(True) self.textUnderline.setText("U") self.horizontalLayout.addWidget(self.textUnderline) self.fontComboBox = QFontComboBox(self.frame) self.horizontalLayout.addWidget(self.fontComboBox) self.setLayout(self.horizontalLayout)
def __init__(self): super(Demo, self).__init__() self.combobox_1 = QComboBox(self) # 1 self.combobox_2 = QFontComboBox(self) # 2 self.lineedit = QLineEdit(self) # 3 self.v_layout = QVBoxLayout() self.layout_init() self.combobox_init()
def __init__(self, parent): super().__init__(parent=parent) to_whomEdit = QLineEdit(self) section_nameEdit = QLineEdit(self) fontChoice = QFontComboBox(self) page_startEdit = QSpinBox(self) page_startEdit.setRange(1, 1000) page_startEdit.setSuffix(' стор.') append_numEdit = QSpinBox(self) append_numEdit.setRange(1, 100) publishGroupBox = QGroupBox('Для публікації', self) publishLayout = QGridLayout(publishGroupBox) publishLayout.addWidget(QLabel('Кому:'), 0, 0) publishLayout.addWidget(to_whomEdit, 0, 1) publishLayout.addWidget(QLabel('Почати з:'), 0, 3) publishLayout.addWidget(page_startEdit, 0, 4) publishLayout.addWidget(QLabel('№ табл./дод.:'), 0, 6) publishLayout.addWidget(append_numEdit, 0, 7) publishLayout.addWidget(QLabel('Назва розділу:'), 1, 0) publishLayout.addWidget(section_nameEdit, 1, 1) publishLayout.addWidget(QLabel('Шрифт:'), 1, 3) publishLayout.addWidget(fontChoice, 1, 4, 1, 4) publishLayout.setColumnMinimumWidth(2, 5) t1Edit = QSpinBox(self) t1Edit.setRange(0, 150) t1Edit.setValue(95) t1Edit.setSuffix(' \N{DEGREE CELSIUS}') t2Edit = QSpinBox(self) t2Edit.setRange(0, 150) t2Edit.setValue(70) t2Edit.setSuffix(' \N{DEGREE CELSIUS}') tLayout = QHBoxLayout() tLayout.addWidget(QLabel('t_1:')) tLayout.addWidget(t1Edit) tLayout.addSpacing(5) tLayout.addWidget(QLabel('t_2:')) tLayout.addWidget(t2Edit) tLayout.addStretch() dPwWidget = KwDPwWidget(self) dPwWidget.layout().setContentsMargins(0, 0, 0, 0) layout = QVBoxLayout(self) layout.addWidget(publishGroupBox) layout.addLayout(tLayout) layout.addWidget(dPwWidget)
def __init__(self, font='', size=10, *args, **kwargs): super().__init__(*args, **kwargs) self.__fontChoice = QFontComboBox(self) self.__fontChoice.setCurrentText(font) self.__fontChoice.currentIndexChanged[str].connect( self.fontChanged.emit) self.__font_sizeEdit = QSpinBox(self) self.__font_sizeEdit.setRange(5, 72) self.__font_sizeEdit.setValue(size) self.__font_sizeEdit.valueChanged[int].connect( self.font_sizeChanged.emit) layout = QHBoxLayout(self) layout.setSpacing(5) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self.__fontChoice) layout.addWidget(self.__font_sizeEdit)
class KwFontDataChoicer(QWidget): u''' @version: 0.1.1 ''' fontChanged = pyqtSignal(str, name='fontChanged') font_sizeChanged = pyqtSignal(int, name='font_sizeChanged') def __init__(self, font='', size=10, *args, **kwargs): super(KwFontDataChoicer, self).__init__(*args, **kwargs) self.__fontChoice = QFontComboBox(self) self.__fontChoice.setCurrentFont(QFont(font)) #.setCurrentText(font) self.__fontChoice.currentIndexChanged[str].connect( self.fontChanged.emit) self.__font_sizeEdit = QSpinBox(self) self.__font_sizeEdit.setRange(5, 72) self.__font_sizeEdit.setValue(size) self.__font_sizeEdit.valueChanged[int].connect( self.font_sizeChanged.emit) layout = QHBoxLayout(self) layout.setSpacing(5) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self.__fontChoice, 1) layout.addWidget(self.__font_sizeEdit, 0) @property def font_data(self): return self.__fontChoice.currentText(), self.__font_sizeEdit.value() @font_data.setter def font_data(self, font, size): self.__fontChoice.setCurrentText(font) self.__font_sizeEdit.setValue(size) @property def font(self): return self.__fontChoice.currentText() @font.setter def font(self, font): self.__fontChoice.setCurrentText(font) @property def size(self): return self.__font_sizeEdit.value() @size.setter def size(self, size): return self.__font_sizeEdit.setValue(size)
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)
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())
def __buildUI(self): ##窗体上动态添加组件 # 创建状态栏上的组件 self.__LabFile = QLabel(self) # QLabel组件显示信息 self.__LabFile.setMinimumWidth(150) self.__LabFile.setText("文件名: ") self.ui.statusBar.addWidget(self.__LabFile) self.__progressBar1 = QProgressBar(self) # progressBar1 self.__progressBar1.setMaximumWidth(200) self.__progressBar1.setMinimum(5) self.__progressBar1.setMaximum(50) sz = self.ui.textEdit.font().pointSize() #字体大小 self.__progressBar1.setValue(sz) self.ui.statusBar.addWidget(self.__progressBar1) self.__LabInfo = QLabel(self) # QLabel组件显示字体名称 self.__LabInfo.setText("选择字体名称: ") self.ui.statusBar.addPermanentWidget(self.__LabInfo) #为actLang_CN和actLang_EN创建QActionGroup,互斥型选择 actionGroup = QActionGroup(self) actionGroup.addAction(self.ui.actLang_CN) actionGroup.addAction(self.ui.actLang_EN) actionGroup.setExclusive(True) #互斥型分组 self.ui.actLang_CN.setChecked(True) #创建工具栏上的组件 self.__spinFontSize = QSpinBox(self) #字体大小spinbox self.__spinFontSize.setMinimum(5) self.__spinFontSize.setMaximum(50) sz = self.ui.textEdit.font().pointSize() self.__spinFontSize.setValue(sz) self.__spinFontSize.setMinimumWidth(50) self.ui.mainToolBar.addWidget(self.__spinFontSize) #SpinBox添加到工具栏 self.__comboFontName = QFontComboBox(self) #字体 combobox self.__comboFontName.setMinimumWidth(100) self.ui.mainToolBar.addWidget(self.__comboFontName) self.ui.mainToolBar.addSeparator() #添加一个分隔条 self.ui.mainToolBar.addAction(self.ui.actClose) #添加 actClose作为“关闭”按钮
def __init__(self): super().__init__() self.fontLabel1 = QLabel() self.fontLabel2 = QLabel() self.fontComboBox = QFontComboBox() self.sizeSpinBox = QSpinBox() self.fontToolBar = QToolBar() self.filename = None self.fCurFileName = None self.initUI()
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 _buildUi(self): # QLable显示信息 self._LabFile = QLabel(self) self._LabFile.setMinimumWidth(150) self._LabFile.setText('文件名:') self._ui.statusBar.addWidget(self._LabFile) # 添加到状态栏 # progressBar显示 self._progressBar1 = QProgressBar(self) self._progressBar1.setMaximumWidth(200) self._progressBar1.setMinimum(5) self._progressBar1.setMaximum(50) sz = self._ui.plainTextEdit.font().pointSize() self._progressBar1.setValue(sz) # 将字体大小显示在progressBar self._ui.statusBar.addWidget(self._progressBar1) # 添加到状态栏 self._LabInfo = QLabel(self) self._LabInfo.setText('选择字体名称:{黑体}') self._ui.statusBar.addPermanentWidget(self._LabInfo) actionGroup = QActionGroup(self) actionGroup.addAction(self._ui.action_English) actionGroup.addAction(self._ui.action_Chinese) actionGroup.setExclusive(True) self._ui.action_Chinese.setChecked(True) self._spinFontSize = QSpinBox(self) self._spinFontSize.setMinimum(5) self._spinFontSize.setMaximum(50) sz = self._ui.plainTextEdit.font().pointSize() self._spinFontSize.setValue(sz) self._spinFontSize.setMinimumWidth(50) self._ui.toolBar.addWidget(self._spinFontSize) self._comboFontName = QFontComboBox(self) self._comboFontName.setMinimumWidth(100) self._ui.toolBar.addWidget(self._comboFontName) self._ui.toolBar.addSeparator() self._ui.toolBar.addAction(self._ui.action_Close)
def fonts(self): # тулбар шрифтов fonts = QFontComboBox(self) # ComboBox-ы шрифтов fonts.setCurrentFont(QFont("Times New Roman")) fonts_sizes = QComboBox(self) font_color = QComboBox(self) italic = QAction(QIcon(r'icons\italic.png'), 'Курсив', self) underline = QAction(QIcon(r'icons\underline.png'), 'Нижнее подчеркивание', self) choosebackground = QAction(QIcon(r'icons\highlighter.png'), 'Фон текста', self) bold = QAction(QIcon(r'icons\bold.png'), 'Полужирный', self) image = QAction(QIcon("icons/image.png"), "Вставить изображение", self) self.fontbar.addAction(image) # добавление в menubar self.fontbar.addWidget(fonts) self.fontbar.addWidget(fonts_sizes) self.fontbar.addWidget(font_color) self.fontbar.addSeparator() self.fontbar.addAction(choosebackground) self.fontbar.addAction(italic) self.fontbar.addAction(underline) self.fontbar.addAction(bold) self.fontbar.addAction(image) image.triggered.connect(self.imageinsert) fonts.currentFontChanged.connect(self.fontchanged) choosebackground.triggered.connect(self.background) fonts_sizes.activated.connect(self.newsize) font_color.activated.connect(self.newcolor) italic.triggered.connect(self.italic) underline.triggered.connect(self.underline) bold.triggered.connect(self.bold) self.text.setFontPointSize(8) for i in self.sizes: fonts_sizes.addItem(i) for j in self.colors.keys(): font_color.addItem(j)
def __buildUI(self): self.__LabFile = QLabel(self)#QLabel组件显示信息 self.__LabFile.setMinimumWidth(150) self.__LabFile.setText('文件名: ') self.ui.statusBar.addWidget(self.__LabFile)#添加到状态栏 self.__progressBar1 = QProgressBar(self)#实例进度条 self.__progressBar1.setMaximumWidth(200)#设定最大宽度 self.__progressBar1.setMinimum(5)#设置最小值 self.__progressBar1.setMaximum(50)#设置最大值 sz = self.ui.textEdit.font().pointSize() print(sz) self.__progressBar1.setValue(sz) self.ui.statusBar.addWidget(self.__progressBar1) self.__LabInfo = QLabel(self) self.__LabInfo.setText('选择字体名称: ') self.ui.statusBar.addPermanentWidget(self.__LabInfo) actionGroup = QActionGroup(self)#定义一个组 actionGroup.addAction(self.ui.actLang_CN)#添加两个组件到一个组内 actionGroup.addAction(self.ui.actLang_EN) actionGroup.setExclusive(True)#令组内组件互斥 self.ui.actLang_CN.setChecked(True)#设定中文按钮为默认 self.__spinFontSize = QSpinBox(self)#设定QSpinBox组件控制字体大小 self.__spinFontSize.setMaximum(50)#最大字体50 self.__spinFontSize.setMinimum(5)#最小字体5 sz = self.ui.textEdit.font().pointSize() self.__spinFontSize.setValue(sz) self.__spinFontSize.setMinimumWidth(50) self.ui.mainToolBar.addWidget(self.__spinFontSize) self.__comboFontName = QFontComboBox(self) self.__comboFontName.setMinimumWidth(100) self.ui.mainToolBar.addWidget(self.__comboFontName) self.ui.mainToolBar.addSeparator() self.ui.mainToolBar.addAction(self.ui.actClose)
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())
def initUi(self): layout = QGridLayout() label = QLabel() combo_box = QFontComboBox() combo_box.currentFontChanged.connect( lambda: self.on_current_font_changed( combo_box, label)) layout.addWidget(combo_box, 0, 0) layout.addWidget(label, 1, 0) self.setLayout(layout)
def set_from(self, edit_these, new_item): self.edit_these = edit_these self.new_item = new_item if edit_these: self.meta = edit_these[0].metadata # self.table.horizontalHeader().hide() self.table.setColumnCount(len(edit_these)) listofblanks = [''] * len(edit_these) self.table.setHorizontalHeaderLabels(listofblanks) self.table.horizontalHeader().setFixedHeight(5) self.table.setRowCount(len(self.meta)) self.table.setVerticalHeaderLabels(self.meta.labels()) column = 0 for edit_this in edit_these: row = 0 for meta_item in self.meta: value = self.meta.value(meta_item, edit_this) if isinstance(value, bool): checkbox = QCheckBox() checkbox.setChecked(value) self.table.setCellWidget(row, column, checkbox) if isinstance(value, Enum): combobox = QComboBox() ui.convenience.set_combo_items(type(value), combobox) ui.convenience.set_combo(combobox, value) self.table.setCellWidget(row, column, combobox) elif meta_item.attribute == 'font': combobox = QFontComboBox() combobox.setCurrentText(value) size_policy = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum) size_policy.setHorizontalStretch(0) size_policy.setVerticalStretch(0) combobox.setSizePolicy(size_policy) combobox.setMinimumSize(QtCore.QSize(50, 22)) combobox.setMaximumSize(QtCore.QSize(16777215, 1010)) self.table.setCellWidget(row, column, combobox) else: # print "row " + str(row) + " col " + str(column) + " = " + str(value) self.table.setItem(row, column, QTableWidgetItem(value)) row += 1 self.col_to_item_dict[column] = edit_this column += 1 else: self.table.setColumnCount(1) self.table.setRowCount(1) self.table.setVerticalHeaderLabels(["Error"]) led = QLineEdit("No items selected to edit") self.table.setItem(-1, 1, QTableWidgetItem(led.text())) self.loaded = True
def __init__(self, settings: Settings): super(SettingsDialog, self).__init__() self.settings = settings self.setWindowTitle("Sticky Note - Settings") self.layout = QFormLayout() self.fontSizeBox = QComboBox(self) for i in settings.getAllFontSizes(): self.fontSizeBox.addItem(str(i)) self.fontSizeBox.setCurrentText(str(settings.getFontSize())) self.layout.addRow("Font size", self.fontSizeBox) self.fontSizeBox.currentIndexChanged.connect(self.fontSizeChanged) self.fontFamilyBox = QFontComboBox(self) self.layout.addRow("Font Family", self.fontFamilyBox) self.fontFamilyBox.setCurrentFont(QFont(settings.getFontFamily())) self.fontFamilyBox.currentIndexChanged.connect(self.fontFamilyChanged) self.colorButton = QPushButton('', self) color = QColor(settings.getFontColor()) self.fontColorChanged(color) self.colorButton.clicked.connect(self.showColors) self.layout.addRow("Font Color", self.colorButton) isAutoStartCheckBox = QCheckBox("Enable start on startup", self) #self.layout.addRow("", isAutoStartCheckBox) isAutoStartCheckBox.stateChanged.connect(self.actionEnableAutoStart) isAutoStartCheckBox.setChecked(settings.getStartOnStartup()) QBtn = QDialogButtonBox.Ok | QDialogButtonBox.Cancel self.buttonBox = QDialogButtonBox(QBtn) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.layout.addRow(self.buttonBox) self.setLayout(self.layout) self.setWindowFlags(Qt.Window) self.setFixedSize(350, 150)
def __init__(self, parent=None): super().__init__() self.parent = parent hlayout = QHBoxLayout() self.setLayout(hlayout) font_combobox = QFontComboBox() font_combobox.setEditable(False) font_combobox.setFixedHeight(30) font_combobox.setStyleSheet("QFontComboBox {background-color: white; color: black; border-radius: 3px;\ border-color: lightgray; border-style: solid; border-width:2px;} \ QFontComboBox::down-arrow {image: url(/usr/share/icons/breeze/actions/24/arrow-down)} \ QFontComboBox::drop-down {border:none;}") font_combobox.setCurrentText(settings().value("Subtitle/font")) hlayout.addWidget(font_combobox) self.color_button = QPushButton() self.color_button.setFixedSize(30, 30) self.color_button.setStyleSheet("QPushButton {border: 1px solid black; border-radius: 3px; \ background-color: %s; }"%(settings().value("Subtitle/color") or QColor("#ffffff")).name()) hlayout.addWidget(self.color_button) self.color_button.clicked.connect(self.colorSelected) font_combobox.currentIndexChanged[str].connect(self.fontChanged)
def _create_fontcombobox(self, name): """Return a combobox for modifying a multiple-getValue setting.""" setting = self.settingItems[name] # Create the combobox and populate it combo = QFontComboBox() combo.setMinimumWidth(100) combo.setMaximumWidth(150) combo.setFontFilters(QFontComboBox.AllFonts) # 设置过滤器 # Ugly event handler! def combo_changed(index): self._changedSettings[name] = combo.currentFont().family() combo.currentFontChanged.connect(combo_changed) # Set the initial getValue, if any def combo_update(value): combo.setCurrentFont(QFont(value)) self._updateActions[name] = combo_update # combo_update(self.currentSettings.get(name, list(SettingEnums.enums[valuetype].values())[0])) return combo
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 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 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)
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 setupTextActions(self): tb = QToolBar(self) tb.setWindowTitle("Format Actions") self.addToolBar(tb) menu = QMenu("F&ormat", self) self.menuBar().addMenu(menu) self.actionTextBold = QAction( QIcon.fromTheme('format-text-bold', QIcon(rsrcPath + '/textbold.png')), "&Bold", self, priority=QAction.LowPriority, shortcut=Qt.CTRL + Qt.Key_B, triggered=self.textBold, checkable=True) bold = QFont() bold.setBold(True) self.actionTextBold.setFont(bold) tb.addAction(self.actionTextBold) menu.addAction(self.actionTextBold) self.actionTextItalic = QAction( QIcon.fromTheme('format-text-italic', QIcon(rsrcPath + '/textitalic.png')), "&Italic", self, priority=QAction.LowPriority, shortcut=Qt.CTRL + Qt.Key_I, triggered=self.textItalic, checkable=True) italic = QFont() italic.setItalic(True) self.actionTextItalic.setFont(italic) tb.addAction(self.actionTextItalic) menu.addAction(self.actionTextItalic) self.actionTextUnderline = QAction( QIcon.fromTheme('format-text-underline', QIcon(rsrcPath + '/textunder.png')), "&Underline", self, priority=QAction.LowPriority, shortcut=Qt.CTRL + Qt.Key_U, triggered=self.textUnderline, checkable=True) underline = QFont() underline.setUnderline(True) self.actionTextUnderline.setFont(underline) tb.addAction(self.actionTextUnderline) menu.addAction(self.actionTextUnderline) menu.addSeparator() grp = QActionGroup(self, triggered=self.textAlign) # Make sure the alignLeft is always left of the alignRight. if QApplication.isLeftToRight(): self.actionAlignLeft = QAction( QIcon.fromTheme('format-justify-left', QIcon(rsrcPath + '/textleft.png')), "&Left", grp) self.actionAlignCenter = QAction( QIcon.fromTheme('format-justify-center', QIcon(rsrcPath + '/textcenter.png')), "C&enter", grp) self.actionAlignRight = QAction( QIcon.fromTheme('format-justify-right', QIcon(rsrcPath + '/textright.png')), "&Right", grp) else: self.actionAlignRight = QAction( QIcon.fromTheme('format-justify-right', QIcon(rsrcPath + '/textright.png')), "&Right", grp) self.actionAlignCenter = QAction( QIcon.fromTheme('format-justify-center', QIcon(rsrcPath + '/textcenter.png')), "C&enter", grp) self.actionAlignLeft = QAction( QIcon.fromTheme('format-justify-left', QIcon(rsrcPath + '/textleft.png')), "&Left", grp) self.actionAlignJustify = QAction( QIcon.fromTheme('format-justify-fill', QIcon(rsrcPath + '/textjustify.png')), "&Justify", grp) self.actionAlignLeft.setShortcut(Qt.CTRL + Qt.Key_L) self.actionAlignLeft.setCheckable(True) self.actionAlignLeft.setPriority(QAction.LowPriority) self.actionAlignCenter.setShortcut(Qt.CTRL + Qt.Key_E) self.actionAlignCenter.setCheckable(True) self.actionAlignCenter.setPriority(QAction.LowPriority) self.actionAlignRight.setShortcut(Qt.CTRL + Qt.Key_R) self.actionAlignRight.setCheckable(True) self.actionAlignRight.setPriority(QAction.LowPriority) self.actionAlignJustify.setShortcut(Qt.CTRL + Qt.Key_J) self.actionAlignJustify.setCheckable(True) self.actionAlignJustify.setPriority(QAction.LowPriority) tb.addActions(grp.actions()) menu.addActions(grp.actions()) menu.addSeparator() pix = QPixmap(16, 16) pix.fill(Qt.black) self.actionTextColor = QAction(QIcon(pix), "&Color...", self, triggered=self.textColor) tb.addAction(self.actionTextColor) menu.addAction(self.actionTextColor) tb = QToolBar(self) tb.setAllowedAreas(Qt.TopToolBarArea | Qt.BottomToolBarArea) tb.setWindowTitle("Format Actions") self.addToolBarBreak(Qt.TopToolBarArea) self.addToolBar(tb) comboStyle = QComboBox(tb) tb.addWidget(comboStyle) comboStyle.addItem("Standard") comboStyle.addItem("Bullet List (Disc)") comboStyle.addItem("Bullet List (Circle)") comboStyle.addItem("Bullet List (Square)") comboStyle.addItem("Ordered List (Decimal)") comboStyle.addItem("Ordered List (Alpha lower)") comboStyle.addItem("Ordered List (Alpha upper)") comboStyle.addItem("Ordered List (Roman lower)") comboStyle.addItem("Ordered List (Roman upper)") comboStyle.activated.connect(self.textStyle) self.comboFont = QFontComboBox(tb) tb.addWidget(self.comboFont) self.comboFont.activated[str].connect(self.textFamily) self.comboSize = QComboBox(tb) self.comboSize.setObjectName("comboSize") tb.addWidget(self.comboSize) self.comboSize.setEditable(True) db = QFontDatabase() for size in db.standardSizes(): self.comboSize.addItem("%s" % (size)) self.comboSize.activated[str].connect(self.textSize) self.comboSize.setCurrentIndex( self.comboSize.findText( "%s" % (QApplication.font().pointSize())))
class TextEdit(QMainWindow): def __init__(self, fileName=None, parent=None): super(TextEdit, self).__init__(parent) self.setWindowIcon(QIcon(':/images/logo.png')) self.setToolButtonStyle(Qt.ToolButtonFollowStyle) self.setupFileActions() self.setupEditActions() self.setupTextActions() helpMenu = QMenu("Help", self) self.menuBar().addMenu(helpMenu) helpMenu.addAction("About", self.about) helpMenu.addAction("About &Qt", QApplication.instance().aboutQt) self.textEdit = QTextEdit(self) self.textEdit.currentCharFormatChanged.connect( self.currentCharFormatChanged) self.textEdit.cursorPositionChanged.connect(self.cursorPositionChanged) self.setCentralWidget(self.textEdit) self.textEdit.setFocus() self.setCurrentFileName() self.fontChanged(self.textEdit.font()) self.colorChanged(self.textEdit.textColor()) self.alignmentChanged(self.textEdit.alignment()) self.textEdit.document().modificationChanged.connect( self.actionSave.setEnabled) self.textEdit.document().modificationChanged.connect( self.setWindowModified) self.textEdit.document().undoAvailable.connect( self.actionUndo.setEnabled) self.textEdit.document().redoAvailable.connect( self.actionRedo.setEnabled) self.setWindowModified(self.textEdit.document().isModified()) self.actionSave.setEnabled(self.textEdit.document().isModified()) self.actionUndo.setEnabled(self.textEdit.document().isUndoAvailable()) self.actionRedo.setEnabled(self.textEdit.document().isRedoAvailable()) self.actionUndo.triggered.connect(self.textEdit.undo) self.actionRedo.triggered.connect(self.textEdit.redo) self.actionCut.setEnabled(False) self.actionCopy.setEnabled(False) self.actionCut.triggered.connect(self.textEdit.cut) self.actionCopy.triggered.connect(self.textEdit.copy) self.actionPaste.triggered.connect(self.textEdit.paste) self.textEdit.copyAvailable.connect(self.actionCut.setEnabled) self.textEdit.copyAvailable.connect(self.actionCopy.setEnabled) QApplication.clipboard().dataChanged.connect(self.clipboardDataChanged) if fileName is None: fileName = ':/example.html' if not self.load(fileName): self.fileNew() def closeEvent(self, e): if self.maybeSave(): e.accept() else: e.ignore() def setupFileActions(self): tb = QToolBar(self) tb.setWindowTitle("File Actions") self.addToolBar(tb) menu = QMenu("&File", self) self.menuBar().addMenu(menu) self.actionNew = QAction( QIcon.fromTheme('document-new', QIcon(rsrcPath + '/filenew.png')), "&New", self, priority=QAction.LowPriority, shortcut=QKeySequence.New, triggered=self.fileNew) tb.addAction(self.actionNew) menu.addAction(self.actionNew) self.actionOpen = QAction( QIcon.fromTheme('document-open', QIcon(rsrcPath + '/fileopen.png')), "&Open...", self, shortcut=QKeySequence.Open, triggered=self.fileOpen) tb.addAction(self.actionOpen) menu.addAction(self.actionOpen) menu.addSeparator() self.actionSave = QAction( QIcon.fromTheme('document-save', QIcon(rsrcPath + '/filesave.png')), "&Save", self, shortcut=QKeySequence.Save, triggered=self.fileSave, enabled=False) tb.addAction(self.actionSave) menu.addAction(self.actionSave) self.actionSaveAs = QAction("Save &As...", self, priority=QAction.LowPriority, shortcut=Qt.CTRL + Qt.SHIFT + Qt.Key_S, triggered=self.fileSaveAs) menu.addAction(self.actionSaveAs) menu.addSeparator() self.actionPrint = QAction( QIcon.fromTheme('document-print', QIcon(rsrcPath + '/fileprint.png')), "&Print...", self, priority=QAction.LowPriority, shortcut=QKeySequence.Print, triggered=self.filePrint) tb.addAction(self.actionPrint) menu.addAction(self.actionPrint) self.actionPrintPreview = QAction( QIcon.fromTheme('fileprint', QIcon(rsrcPath + '/fileprint.png')), "Print Preview...", self, shortcut=Qt.CTRL + Qt.SHIFT + Qt.Key_P, triggered=self.filePrintPreview) menu.addAction(self.actionPrintPreview) self.actionPrintPdf = QAction( QIcon.fromTheme('exportpdf', QIcon(rsrcPath + '/exportpdf.png')), "&Export PDF...", self, priority=QAction.LowPriority, shortcut=Qt.CTRL + Qt.Key_D, triggered=self.filePrintPdf) tb.addAction(self.actionPrintPdf) menu.addAction(self.actionPrintPdf) menu.addSeparator() self.actionQuit = QAction("&Quit", self, shortcut=QKeySequence.Quit, triggered=self.close) menu.addAction(self.actionQuit) def setupEditActions(self): tb = QToolBar(self) tb.setWindowTitle("Edit Actions") self.addToolBar(tb) menu = QMenu("&Edit", self) self.menuBar().addMenu(menu) self.actionUndo = QAction( QIcon.fromTheme('edit-undo', QIcon(rsrcPath + '/editundo.png')), "&Undo", self, shortcut=QKeySequence.Undo) tb.addAction(self.actionUndo) menu.addAction(self.actionUndo) self.actionRedo = QAction( QIcon.fromTheme('edit-redo', QIcon(rsrcPath + '/editredo.png')), "&Redo", self, priority=QAction.LowPriority, shortcut=QKeySequence.Redo) tb.addAction(self.actionRedo) menu.addAction(self.actionRedo) menu.addSeparator() self.actionCut = QAction( QIcon.fromTheme('edit-cut', QIcon(rsrcPath + '/editcut.png')), "Cu&t", self, priority=QAction.LowPriority, shortcut=QKeySequence.Cut) tb.addAction(self.actionCut) menu.addAction(self.actionCut) self.actionCopy = QAction( QIcon.fromTheme('edit-copy', QIcon(rsrcPath + '/editcopy.png')), "&Copy", self, priority=QAction.LowPriority, shortcut=QKeySequence.Copy) tb.addAction(self.actionCopy) menu.addAction(self.actionCopy) self.actionPaste = QAction( QIcon.fromTheme('edit-paste', QIcon(rsrcPath + '/editpaste.png')), "&Paste", self, priority=QAction.LowPriority, shortcut=QKeySequence.Paste, enabled=(len(QApplication.clipboard().text()) != 0)) tb.addAction(self.actionPaste) menu.addAction(self.actionPaste) def setupTextActions(self): tb = QToolBar(self) tb.setWindowTitle("Format Actions") self.addToolBar(tb) menu = QMenu("F&ormat", self) self.menuBar().addMenu(menu) self.actionTextBold = QAction( QIcon.fromTheme('format-text-bold', QIcon(rsrcPath + '/textbold.png')), "&Bold", self, priority=QAction.LowPriority, shortcut=Qt.CTRL + Qt.Key_B, triggered=self.textBold, checkable=True) bold = QFont() bold.setBold(True) self.actionTextBold.setFont(bold) tb.addAction(self.actionTextBold) menu.addAction(self.actionTextBold) self.actionTextItalic = QAction( QIcon.fromTheme('format-text-italic', QIcon(rsrcPath + '/textitalic.png')), "&Italic", self, priority=QAction.LowPriority, shortcut=Qt.CTRL + Qt.Key_I, triggered=self.textItalic, checkable=True) italic = QFont() italic.setItalic(True) self.actionTextItalic.setFont(italic) tb.addAction(self.actionTextItalic) menu.addAction(self.actionTextItalic) self.actionTextUnderline = QAction( QIcon.fromTheme('format-text-underline', QIcon(rsrcPath + '/textunder.png')), "&Underline", self, priority=QAction.LowPriority, shortcut=Qt.CTRL + Qt.Key_U, triggered=self.textUnderline, checkable=True) underline = QFont() underline.setUnderline(True) self.actionTextUnderline.setFont(underline) tb.addAction(self.actionTextUnderline) menu.addAction(self.actionTextUnderline) menu.addSeparator() grp = QActionGroup(self, triggered=self.textAlign) # Make sure the alignLeft is always left of the alignRight. if QApplication.isLeftToRight(): self.actionAlignLeft = QAction( QIcon.fromTheme('format-justify-left', QIcon(rsrcPath + '/textleft.png')), "&Left", grp) self.actionAlignCenter = QAction( QIcon.fromTheme('format-justify-center', QIcon(rsrcPath + '/textcenter.png')), "C&enter", grp) self.actionAlignRight = QAction( QIcon.fromTheme('format-justify-right', QIcon(rsrcPath + '/textright.png')), "&Right", grp) else: self.actionAlignRight = QAction( QIcon.fromTheme('format-justify-right', QIcon(rsrcPath + '/textright.png')), "&Right", grp) self.actionAlignCenter = QAction( QIcon.fromTheme('format-justify-center', QIcon(rsrcPath + '/textcenter.png')), "C&enter", grp) self.actionAlignLeft = QAction( QIcon.fromTheme('format-justify-left', QIcon(rsrcPath + '/textleft.png')), "&Left", grp) self.actionAlignJustify = QAction( QIcon.fromTheme('format-justify-fill', QIcon(rsrcPath + '/textjustify.png')), "&Justify", grp) self.actionAlignLeft.setShortcut(Qt.CTRL + Qt.Key_L) self.actionAlignLeft.setCheckable(True) self.actionAlignLeft.setPriority(QAction.LowPriority) self.actionAlignCenter.setShortcut(Qt.CTRL + Qt.Key_E) self.actionAlignCenter.setCheckable(True) self.actionAlignCenter.setPriority(QAction.LowPriority) self.actionAlignRight.setShortcut(Qt.CTRL + Qt.Key_R) self.actionAlignRight.setCheckable(True) self.actionAlignRight.setPriority(QAction.LowPriority) self.actionAlignJustify.setShortcut(Qt.CTRL + Qt.Key_J) self.actionAlignJustify.setCheckable(True) self.actionAlignJustify.setPriority(QAction.LowPriority) tb.addActions(grp.actions()) menu.addActions(grp.actions()) menu.addSeparator() pix = QPixmap(16, 16) pix.fill(Qt.black) self.actionTextColor = QAction(QIcon(pix), "&Color...", self, triggered=self.textColor) tb.addAction(self.actionTextColor) menu.addAction(self.actionTextColor) tb = QToolBar(self) tb.setAllowedAreas(Qt.TopToolBarArea | Qt.BottomToolBarArea) tb.setWindowTitle("Format Actions") self.addToolBarBreak(Qt.TopToolBarArea) self.addToolBar(tb) comboStyle = QComboBox(tb) tb.addWidget(comboStyle) comboStyle.addItem("Standard") comboStyle.addItem("Bullet List (Disc)") comboStyle.addItem("Bullet List (Circle)") comboStyle.addItem("Bullet List (Square)") comboStyle.addItem("Ordered List (Decimal)") comboStyle.addItem("Ordered List (Alpha lower)") comboStyle.addItem("Ordered List (Alpha upper)") comboStyle.addItem("Ordered List (Roman lower)") comboStyle.addItem("Ordered List (Roman upper)") comboStyle.activated.connect(self.textStyle) self.comboFont = QFontComboBox(tb) tb.addWidget(self.comboFont) self.comboFont.activated[str].connect(self.textFamily) self.comboSize = QComboBox(tb) self.comboSize.setObjectName("comboSize") tb.addWidget(self.comboSize) self.comboSize.setEditable(True) db = QFontDatabase() for size in db.standardSizes(): self.comboSize.addItem("%s" % (size)) self.comboSize.activated[str].connect(self.textSize) self.comboSize.setCurrentIndex( self.comboSize.findText( "%s" % (QApplication.font().pointSize()))) def load(self, f): if not QFile.exists(f): return False fh = QFile(f) if not fh.open(QFile.ReadOnly): return False data = fh.readAll() codec = QTextCodec.codecForHtml(data) unistr = codec.toUnicode(data) if Qt.mightBeRichText(unistr): self.textEdit.setHtml(unistr) else: self.textEdit.setPlainText(unistr) self.setCurrentFileName(f) return True def maybeSave(self): if not self.textEdit.document().isModified(): return True if self.fileName.startswith(':/'): return True ret = QMessageBox.warning(self, "Application", "The document has been modified.\n" "Do you want to save your changes?", QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel) if ret == QMessageBox.Save: return self.fileSave() if ret == QMessageBox.Cancel: return False return True def setCurrentFileName(self, fileName=''): self.fileName = fileName self.textEdit.document().setModified(False) if not fileName: shownName = 'untitled.txt' else: shownName = QFileInfo(fileName).fileName() self.setWindowTitle(self.tr("%s[*] - %s" % (shownName, "Rich Text"))) self.setWindowModified(False) def fileNew(self): if self.maybeSave(): self.textEdit.clear() self.setCurrentFileName() def fileOpen(self): fn, _ = QFileDialog.getOpenFileName(self, "Open File...", None, "HTML-Files (*.htm *.html);;All Files (*)") if fn: self.load(fn) def fileSave(self): if not self.fileName: return self.fileSaveAs() writer = QTextDocumentWriter(self.fileName) success = writer.write(self.textEdit.document()) if success: self.textEdit.document().setModified(False) return success def fileSaveAs(self): fn, _ = QFileDialog.getSaveFileName(self, "Save as...", None, "ODF files (*.odt);;HTML-Files (*.htm *.html);;All Files (*)") if not fn: return False lfn = fn.lower() if not lfn.endswith(('.odt', '.htm', '.html')): # The default. fn += '.odt' self.setCurrentFileName(fn) return self.fileSave() def filePrint(self): printer = QPrinter(QPrinter.HighResolution) dlg = QPrintDialog(printer, self) if self.textEdit.textCursor().hasSelection(): dlg.addEnabledOption(QPrintDialog.PrintSelection) dlg.setWindowTitle("Print Document") if dlg.exec_() == QPrintDialog.Accepted: self.textEdit.print_(printer) del dlg def filePrintPreview(self): printer = QPrinter(QPrinter.HighResolution) preview = QPrintPreviewDialog(printer, self) preview.paintRequested.connect(self.printPreview) preview.exec_() def printPreview(self, printer): self.textEdit.print_(printer) def filePrintPdf(self): fn, _ = QFileDialog.getSaveFileName(self, "Export PDF", None, "PDF files (*.pdf);;All Files (*)") if fn: if QFileInfo(fn).suffix().isEmpty(): fn += '.pdf' printer = QPrinter(QPrinter.HighResolution) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(fn) self.textEdit.document().print_(printer) def textBold(self): fmt = QTextCharFormat() fmt.setFontWeight(self.actionTextBold.isChecked() and QFont.Bold or QFont.Normal) self.mergeFormatOnWordOrSelection(fmt) def textUnderline(self): fmt = QTextCharFormat() fmt.setFontUnderline(self.actionTextUnderline.isChecked()) self.mergeFormatOnWordOrSelection(fmt) def textItalic(self): fmt = QTextCharFormat() fmt.setFontItalic(self.actionTextItalic.isChecked()) self.mergeFormatOnWordOrSelection(fmt) def textFamily(self, family): fmt = QTextCharFormat() fmt.setFontFamily(family) self.mergeFormatOnWordOrSelection(fmt) def textSize(self, pointSize): pointSize = float(pointSize) if pointSize > 0: fmt = QTextCharFormat() fmt.setFontPointSize(pointSize) self.mergeFormatOnWordOrSelection(fmt) def textStyle(self, styleIndex): cursor = self.textEdit.textCursor() if styleIndex: styleDict = { 1: QTextListFormat.ListDisc, 2: QTextListFormat.ListCircle, 3: QTextListFormat.ListSquare, 4: QTextListFormat.ListDecimal, 5: QTextListFormat.ListLowerAlpha, 6: QTextListFormat.ListUpperAlpha, 7: QTextListFormat.ListLowerRoman, 8: QTextListFormat.ListUpperRoman, } style = styleDict.get(styleIndex, QTextListFormat.ListDisc) cursor.beginEditBlock() blockFmt = cursor.blockFormat() listFmt = QTextListFormat() if cursor.currentList(): listFmt = cursor.currentList().format() else: listFmt.setIndent(blockFmt.indent() + 1) blockFmt.setIndent(0) cursor.setBlockFormat(blockFmt) listFmt.setStyle(style) cursor.createList(listFmt) cursor.endEditBlock() else: bfmt = QTextBlockFormat() bfmt.setObjectIndex(-1) cursor.mergeBlockFormat(bfmt) def textColor(self): col = QColorDialog.getColor(self.textEdit.textColor(), self) if not col.isValid(): return fmt = QTextCharFormat() fmt.setForeground(col) self.mergeFormatOnWordOrSelection(fmt) self.colorChanged(col) def textAlign(self, action): if action == self.actionAlignLeft: self.textEdit.setAlignment(Qt.AlignLeft | Qt.AlignAbsolute) elif action == self.actionAlignCenter: self.textEdit.setAlignment(Qt.AlignHCenter) elif action == self.actionAlignRight: self.textEdit.setAlignment(Qt.AlignRight | Qt.AlignAbsolute) elif action == self.actionAlignJustify: self.textEdit.setAlignment(Qt.AlignJustify) def currentCharFormatChanged(self, format): self.fontChanged(format.font()) self.colorChanged(format.foreground().color()) def cursorPositionChanged(self): self.alignmentChanged(self.textEdit.alignment()) def clipboardDataChanged(self): self.actionPaste.setEnabled(len(QApplication.clipboard().text()) != 0) def about(self): QMessageBox.about(self, "About", "This example demonstrates Qt's rich text editing facilities " "in action, providing an example document for you to " "experiment with.") def mergeFormatOnWordOrSelection(self, format): cursor = self.textEdit.textCursor() if not cursor.hasSelection(): cursor.select(QTextCursor.WordUnderCursor) cursor.mergeCharFormat(format) self.textEdit.mergeCurrentCharFormat(format) def fontChanged(self, font): self.comboFont.setCurrentIndex( self.comboFont.findText(QFontInfo(font).family())) self.comboSize.setCurrentIndex( self.comboSize.findText("%s" % font.pointSize())) self.actionTextBold.setChecked(font.bold()) self.actionTextItalic.setChecked(font.italic()) self.actionTextUnderline.setChecked(font.underline()) def colorChanged(self, color): pix = QPixmap(16, 16) pix.fill(color) self.actionTextColor.setIcon(QIcon(pix)) def alignmentChanged(self, alignment): if alignment & Qt.AlignLeft: self.actionAlignLeft.setChecked(True) elif alignment & Qt.AlignHCenter: self.actionAlignCenter.setChecked(True) elif alignment & Qt.AlignRight: self.actionAlignRight.setChecked(True) elif alignment & Qt.AlignJustify: self.actionAlignJustify.setChecked(True)
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)
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")
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)
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 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): 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))