def test_should_set_config_checkedvalue_on_true(): checkbox = QCheckBox() assert not checkbox.isChecked() widget = CheckboxWidget(widget=checkbox) widget.config = config widget.setvalue('MyTrue') assert checkbox.isChecked()
def test_should_set_config_checkedvalue_on_true(): checkbox = QCheckBox() assert not checkbox.isChecked() widget = CheckboxWidget(widget=checkbox) widget.config = config widget.setvalue('MyTrue') assert checkbox.isChecked()
class Running(preferences.Group): def __init__(self, page): super(Running, self).__init__(page) layout = QVBoxLayout() self.setLayout(layout) self.saveDocument = QCheckBox(clicked=self.changed) self.deleteFiles = QCheckBox(clicked=self.changed) self.embedSourceCode = QCheckBox(clicked=self.changed) self.noTranslation = QCheckBox(clicked=self.changed) self.includeLabel = QLabel() self.include = widgets.listedit.FilePathEdit() self.include.listBox.setDragDropMode(QAbstractItemView.InternalMove) self.include.changed.connect(self.changed) layout.addWidget(self.saveDocument) layout.addWidget(self.deleteFiles) layout.addWidget(self.embedSourceCode) layout.addWidget(self.noTranslation) layout.addWidget(self.includeLabel) layout.addWidget(self.include) app.translateUI(self) def translateUI(self): self.setTitle(_("Running LilyPond")) self.saveDocument.setText(_("Save document if possible")) self.saveDocument.setToolTip(_( "If checked, the document is saved when it is local and modified.\n" "Otherwise a temporary file is used to run LilyPond.")) self.deleteFiles.setText(_("Delete intermediate output files")) self.deleteFiles.setToolTip(_( "If checked, LilyPond will delete intermediate PostScript files.")) self.embedSourceCode.setText(_("Embed Source Code files in publish mode")) self.embedSourceCode.setToolTip(_( "If checked, the LilyPond source files will be embedded in the PDF\n" "when LilyPond is started in publish mode.\n" "This feature is available since LilyPond 2.19.39.")) self.noTranslation.setText(_("Run LilyPond with English messages")) self.noTranslation.setToolTip(_( "If checked, LilyPond's output messages will be in English.\n" "This can be useful for bug reports.")) self.includeLabel.setText(_("LilyPond include path:")) def loadSettings(self): s = settings() self.saveDocument.setChecked(s.value("save_on_run", False, bool)) self.deleteFiles.setChecked(s.value("delete_intermediate_files", True, bool)) self.embedSourceCode.setChecked(s.value("embed_source_code", False, bool)) self.noTranslation.setChecked(s.value("no_translation", False, bool)) include_path = qsettings.get_string_list(s, "include_path") self.include.setValue(include_path) def saveSettings(self): s = settings() s.setValue("save_on_run", self.saveDocument.isChecked()) s.setValue("delete_intermediate_files", self.deleteFiles.isChecked()) s.setValue("embed_source_code", self.embedSourceCode.isChecked()) s.setValue("no_translation", self.noTranslation.isChecked()) s.setValue("include_path", self.include.value())
def test_should_set_config_uncheckedvalue_on_false(): checkbox = QCheckBox() checkbox.setChecked(True) assert checkbox.isChecked() widget = CheckboxWidget(widget=checkbox) widget.config = config widget.setvalue('MyFalse') assert not checkbox.isChecked()
def test_should_set_config_uncheckedvalue_on_false(): checkbox = QCheckBox() checkbox.setChecked(True) assert checkbox.isChecked() widget = CheckboxWidget(widget=checkbox) widget.config = config widget.setvalue('MyFalse') assert not checkbox.isChecked()
class LilyPondInfoDialog(KDialog): """ A dialog to edit attributes of a LilyPondInfo instance. """ def __init__(self, parent): KDialog.__init__(self, parent) self.setButtons(KDialog.ButtonCode(KDialog.Ok | KDialog.Cancel | KDialog.Help | KDialog.User1)) self.setCaption(i18n("LilyPond")) self.setHelp("settings-paths-lilypond") self.setButtonText(KDialog.User1, i18n("Download...")) self.setButtonIcon(KDialog.User1, KIcon("download")) self.setButtonToolTip(KDialog.User1, i18n("Download new binary LilyPond releases.")) self.user1Clicked.connect(self.downloadLilyPond) layout = QGridLayout(self.mainWidget()) l = QLabel(i18n("LilyPond Command:")) self.lilypond = KUrlRequester() l.setBuddy(self.lilypond) self.lilypond.lineEdit().setToolTip(i18n("Name or full path of the LilyPond program.")) self.lilypond.fileDialog().setCaption(i18n("LilyPond Command")) layout.addWidget(l, 0, 0, 1, 2) layout.addWidget(self.lilypond, 1, 0, 1, 2) self.commands = {} row = 2 for name, description in LilyPondInfo.commandNames(): l = QLabel(description) e = self.commands[name] = QLineEdit() l.setBuddy(e) layout.addWidget(l, row, 0, Qt.AlignRight) layout.addWidget(e, row, 1) row += 1 self.default = QCheckBox(i18n("Set as default")) layout.addWidget(self.default, row, 1) self.auto = QCheckBox(i18n("Include in automatic version selection")) layout.addWidget(self.auto, row + 1, 1) def loadInfo(self, info): """ Display the settings in the LilyPondInfo object in our dialog. """ self.lilypond.setText(info.lilypond) for name, value in info.commands.items(): self.commands[name].setText(value) self.default.setChecked(info.default) self.auto.setChecked(info.auto) def saveInfo(self, info): """ Write the settings in our dialog to the LilyPondInfo object. """ info.lilypond = self.lilypond.text() for name, widget in self.commands.items(): info.commands[name] = widget.text() info.default = self.default.isChecked() info.auto = self.auto.isChecked() def downloadLilyPond(self): from frescobaldi_app.download import LilyPondDownloadDialog LilyPondDownloadDialog(self).exec_()
class GeneralPreferences(QWidget): """The general preferences input.""" def __init__(self): super(GeneralPreferences, self).__init__() grid = QGridLayout(self) grid.setSpacing(20) grid.setColumnStretch(1, 10) # directory auto completer completer = QCompleter(self) dirs = QDirModel(self) dirs.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot) completer.setModel(dirs) completer.setCaseSensitivity(Qt.CaseInsensitive) completer.setCompletionMode(QCompleter.PopupCompletion) l = QLabel( u"<b>Ingresá el directorio donde descargar los videos...</b>") l.setTextFormat(Qt.RichText) grid.addWidget(l, 0, 0, 1, 2) grid.addWidget(QLabel(u"Descargar en:"), 1, 0, 2, 1) prv = config.get('downloaddir', '') self.downloaddir_entry = QLineEdit(prv) self.downloaddir_entry.setCompleter(completer) self.downloaddir_entry.setPlaceholderText(u'Ingresá un directorio') grid.addWidget(self.downloaddir_entry, 1, 1, 2, 2) self.downloaddir_buttn = QPushButton(u"Elegir un directorio") self.downloaddir_buttn.clicked.connect(self._choose_dir) grid.addWidget(self.downloaddir_buttn, 2, 1, 3, 2) self.autoreload_checkbox = QCheckBox( u"Recargar automáticamente la lista de episodios al iniciar") prv = config.get('autorefresh', False) self.autoreload_checkbox.setChecked(prv) grid.addWidget(self.autoreload_checkbox, 3, 0, 4, 2) self.shownotifs_checkbox = QCheckBox( u"Mostrar una notificación cuando termina cada descarga") prv = config.get('notification', True) self.shownotifs_checkbox.setChecked(prv) grid.addWidget(self.shownotifs_checkbox, 4, 0, 5, 2) def _choose_dir(self): """Choose a directory using a dialog.""" resp = QFileDialog.getExistingDirectory(self, '', os.path.expanduser("~")) if resp: self.downloaddir_entry.setText(resp) def get_config(self): """Return the config for this tab.""" d = {} d['downloaddir'] = self.downloaddir_entry.text() d['autorefresh'] = self.autoreload_checkbox.isChecked() d['notification'] = self.shownotifs_checkbox.isChecked() return d
class GeneralPreferences(QWidget): """The general preferences input.""" def __init__(self): super(GeneralPreferences, self).__init__() grid = QGridLayout(self) grid.setSpacing(20) grid.setColumnStretch(1, 10) # directory auto completer completer = QCompleter(self) dirs = QDirModel(self) dirs.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot) completer.setModel(dirs) completer.setCaseSensitivity(Qt.CaseInsensitive) completer.setCompletionMode(QCompleter.PopupCompletion) l = QLabel( u"<b>Ingresá el directorio donde descargar los videos...</b>") l.setTextFormat(Qt.RichText) grid.addWidget(l, 0, 0, 1, 2) grid.addWidget(QLabel(u"Descargar en:"), 1, 0, 2, 1) prv = config.get('downloaddir', '') self.downloaddir_entry = QLineEdit(prv) self.downloaddir_entry.setCompleter(completer) self.downloaddir_entry.setPlaceholderText(u'Ingresá un directorio') grid.addWidget(self.downloaddir_entry, 1, 1, 2, 2) self.downloaddir_buttn = QPushButton(u"Elegir un directorio") self.downloaddir_buttn.clicked.connect(self._choose_dir) grid.addWidget(self.downloaddir_buttn, 2, 1, 3, 2) self.autoreload_checkbox = QCheckBox( u"Recargar automáticamente la lista de episodios al iniciar") prv = config.get('autorefresh', False) self.autoreload_checkbox.setChecked(prv) grid.addWidget(self.autoreload_checkbox, 3, 0, 4, 2) self.shownotifs_checkbox = QCheckBox( u"Mostrar una notificación cuando termina cada descarga") prv = config.get('notification', True) self.shownotifs_checkbox.setChecked(prv) grid.addWidget(self.shownotifs_checkbox, 4, 0, 5, 2) def _choose_dir(self): """Choose a directory using a dialog.""" resp = QFileDialog.getExistingDirectory(self, '', os.path.expanduser("~")) if resp: self.downloaddir_entry.setText(resp) def get_config(self): """Return the config for this tab.""" d = {} d['downloaddir'] = self.downloaddir_entry.text() d['autorefresh'] = self.autoreload_checkbox.isChecked() d['notification'] = self.shownotifs_checkbox.isChecked() return d
def getArguments(self, parent=None): description = "The CSV export requires some information before it starts:" dialog = CustomDialog("CSV Export", description, parent) default_csv_output_path = self.getDataKWValue("CSV_OUTPUT_PATH", default="output.csv") output_path_model = PathModel(default_csv_output_path) output_path_chooser = PathChooser(output_path_model) design_matrix_default = self.getDataKWValue("DESIGN_MATRIX_PATH", default="") design_matrix_path_model = PathModel(design_matrix_default, is_required=False, must_exist=True) design_matrix_path_chooser = PathChooser(design_matrix_path_model) list_edit = ListEditBox(self.getAllCaseList()) infer_iteration_check = QCheckBox() infer_iteration_check.setChecked(True) infer_iteration_check.setToolTip(CSVExportJob.INFER_HELP) drop_const_columns_check = QCheckBox() drop_const_columns_check.setChecked(False) drop_const_columns_check.setToolTip( "If checked, exclude columns whose value is the same for every entry" ) dialog.addLabeledOption("Output file path", output_path_chooser) dialog.addLabeledOption("Design matrix path", design_matrix_path_chooser) dialog.addLabeledOption("List of cases to export", list_edit) dialog.addLabeledOption("Infer iteration number", infer_iteration_check) dialog.addLabeledOption("Drop constant columns", drop_const_columns_check) dialog.addButtons() success = dialog.showAndTell() if success: design_matrix_path = design_matrix_path_model.getPath() if design_matrix_path.strip() == "": design_matrix_path = None case_list = ",".join(list_edit.getItems()) return [ output_path_model.getPath(), case_list, design_matrix_path, infer_iteration_check.isChecked(), drop_const_columns_check.isChecked(), ] raise CancelPluginException("User cancelled!")
class SourceExport(preferences.Group): def __init__(self, page): super(SourceExport, self).__init__(page) layout = QVBoxLayout() self.setLayout(layout) self.numberLines = QCheckBox(toggled=self.changed) self.inlineStyleCopy = QCheckBox(toggled=self.changed) self.copyHtmlAsPlainText = QCheckBox(toggled=self.changed) self.inlineStyleExport = QCheckBox(toggled=self.changed) layout.addWidget(self.numberLines) layout.addWidget(self.inlineStyleCopy) layout.addWidget(self.inlineStyleExport) layout.addWidget(self.copyHtmlAsPlainText) app.translateUI(self) def translateUI(self): self.setTitle(_("Source Export Preferences")) self.numberLines.setText(_("Show line numbers")) self.numberLines.setToolTip('<qt>' + _( "If enabled, line numbers are shown in exported HTML or printed " "source.")) self.inlineStyleCopy.setText(_("Use inline style when copying colored HTML")) self.inlineStyleCopy.setToolTip('<qt>' + _( "If enabled, inline style attributes are used when copying " "colored HTML to the clipboard. " "Otherwise, a CSS stylesheet is embedded.")) self.inlineStyleExport.setText(_("Use inline style when exporting colored HTML")) self.inlineStyleExport.setToolTip('<qt>' + _( "If enabled, inline style attributes are used when exporing " "colored HTML to a file. " "Otherwise, a CSS stylesheet is embedded.")) self.copyHtmlAsPlainText.setText(_("Copy HTML as plain text")) self.copyHtmlAsPlainText.setToolTip('<qt>' + _( "If enabled, HTML is copied to the clipboard as plain text. " "Use this when you want to type HTML formatted code in a " "plain text editing environment.")) def loadSettings(self): s = QSettings() s.beginGroup("source_export") self.numberLines.setChecked(s.value("number_lines", False, bool)) self.inlineStyleCopy.setChecked(s.value("inline_copy", True, bool)) self.inlineStyleExport.setChecked(s.value("inline_export", False, bool)) self.copyHtmlAsPlainText.setChecked(s.value("copy_html_as_plain_text", False, bool)) def saveSettings(self): s = QSettings() s.beginGroup("source_export") s.setValue("number_lines", self.numberLines.isChecked()) s.setValue("inline_copy", self.inlineStyleCopy.isChecked()) s.setValue("inline_export", self.inlineStyleExport.isChecked()) s.setValue("copy_html_as_plain_text", self.copyHtmlAsPlainText.isChecked())
class DeletionOptions(QDialog): def __init__(self, parent, model): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint QDialog.__init__(self, parent, flags) self.model = model self._setupUi() self.model.view = self self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) def _setupUi(self): self.setWindowTitle(tr("Deletion Options")) self.resize(400, 270) self.verticalLayout = QVBoxLayout(self) self.msgLabel = QLabel() self.verticalLayout.addWidget(self.msgLabel) self.linkCheckbox = QCheckBox(tr("Link deleted files")) self.verticalLayout.addWidget(self.linkCheckbox) text = tr("After having deleted a duplicate, place a link targeting the reference file " "to replace the deleted file.") self.linkMessageLabel = QLabel(text) self.linkMessageLabel.setWordWrap(True) self.verticalLayout.addWidget(self.linkMessageLabel) self.linkTypeRadio = RadioBox(items=[tr("Symlink"), tr("Hardlink")], spread=False) self.verticalLayout.addWidget(self.linkTypeRadio) if not self.model.supports_links(): self.linkCheckbox.setEnabled(False) self.linkTypeRadio.setEnabled(False) self.linkCheckbox.setText(self.linkCheckbox.text() + tr(" (unsupported)")) self.directCheckbox = QCheckBox(tr("Directly delete files")) self.verticalLayout.addWidget(self.directCheckbox) text = tr("Instead of sending files to trash, delete them directly. This option is usually " "used as a workaround when the normal deletion method doesn't work.") self.directMessageLabel = QLabel(text) self.directMessageLabel.setWordWrap(True) self.verticalLayout.addWidget(self.directMessageLabel) self.buttonBox = QDialogButtonBox() self.buttonBox.addButton(tr("Proceed"), QDialogButtonBox.AcceptRole) self.buttonBox.addButton(tr("Cancel"), QDialogButtonBox.RejectRole) self.verticalLayout.addWidget(self.buttonBox) #--- model --> view def update_msg(self, msg): self.msgLabel.setText(msg) def show(self): self.linkCheckbox.setChecked(self.model.link_deleted) self.linkTypeRadio.selected_index = 1 if self.model.use_hardlinks else 0 self.directCheckbox.setChecked(self.model.direct) result = self.exec() self.model.link_deleted = self.linkCheckbox.isChecked() self.model.use_hardlinks = self.linkTypeRadio.selected_index == 1 self.model.direct = self.directCheckbox.isChecked() return result == QDialog.Accepted
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) 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.""")) def loadSettings(self): s = QSettings() s.beginGroup("log") font = QFont(s.value("fontfamily", "monospace")) font.setPointSizeF(float(s.value("fontsize", 9.0))) 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) not in (False, "false")) self.rawview.setChecked(s.value("rawview", True) not in (False, "false")) 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())
class SavingDocument(preferences.Group): def __init__(self, page): super(SavingDocument, self).__init__(page) layout = QVBoxLayout() self.setLayout(layout) self.stripwsp = QCheckBox(toggled=self.changed) self.backup = QCheckBox(toggled=self.changed) self.metainfo = QCheckBox(toggled=self.changed) layout.addWidget(self.stripwsp) layout.addWidget(self.backup) layout.addWidget(self.metainfo) hbox = QHBoxLayout() layout.addLayout(hbox) self.basedirLabel = l = QLabel() self.basedir = UrlRequester() hbox.addWidget(self.basedirLabel) hbox.addWidget(self.basedir) self.basedir.changed.connect(self.changed) app.translateUI(self) def translateUI(self): self.setTitle(_("When saving documents")) self.stripwsp.setText(_("Strip trailing whitespace")) self.stripwsp.setToolTip( _("If checked, Frescobaldi will remove unnecessary whitespace at the " "end of lines (but not inside multi-line strings).")) self.backup.setText(_("Keep backup copy")) self.backup.setToolTip( _("Frescobaldi always backups a file before overwriting it " "with a new version.\n" "If checked those backup copies are retained.")) self.metainfo.setText(_("Remember cursor position, bookmarks, etc.")) self.basedirLabel.setText(_("Default directory:")) self.basedirLabel.setToolTip( _("The default folder for your LilyPond documents (optional).")) def loadSettings(self): s = QSettings() self.stripwsp.setChecked( s.value("strip_trailing_whitespace", False, bool)) self.backup.setChecked(s.value("backup_keep", False, bool)) self.metainfo.setChecked(s.value("metainfo", True, bool)) self.basedir.setPath(s.value("basedir", "", type(""))) def saveSettings(self): s = QSettings() s.setValue("strip_trailing_whitespace", self.stripwsp.isChecked()) s.setValue("backup_keep", self.backup.isChecked()) s.setValue("metainfo", self.metainfo.isChecked()) s.setValue("basedir", self.basedir.path())
class SavingDocument(preferences.Group): def __init__(self, page): super(SavingDocument, self).__init__(page) layout = QVBoxLayout() self.setLayout(layout) self.stripwsp = QCheckBox(toggled=self.changed) self.backup = QCheckBox(toggled=self.changed) self.metainfo = QCheckBox(toggled=self.changed) layout.addWidget(self.stripwsp) layout.addWidget(self.backup) layout.addWidget(self.metainfo) hbox = QHBoxLayout() layout.addLayout(hbox) self.basedirLabel = l = QLabel() self.basedir = UrlRequester() hbox.addWidget(self.basedirLabel) hbox.addWidget(self.basedir) self.basedir.changed.connect(self.changed) app.translateUI(self) def translateUI(self): self.setTitle(_("When saving documents")) self.stripwsp.setText(_("Strip trailing whitespace")) self.stripwsp.setToolTip(_( "If checked, Frescobaldi will remove unnecessary whitespace at the " "end of lines (but not inside multi-line strings).")) self.backup.setText(_("Keep backup copy")) self.backup.setToolTip(_( "Frescobaldi always backups a file before overwriting it " "with a new version.\n" "If checked those backup copies are retained.")) self.metainfo.setText(_("Remember cursor position, bookmarks, etc.")) self.basedirLabel.setText(_("Default directory:")) self.basedirLabel.setToolTip(_("The default folder for your LilyPond documents (optional).")) def loadSettings(self): s = QSettings() self.stripwsp.setChecked(s.value("strip_trailing_whitespace", False, bool)) self.backup.setChecked(s.value("backup_keep", False, bool)) self.metainfo.setChecked(s.value("metainfo", True, bool)) self.basedir.setPath(s.value("basedir", "", type(""))) def saveSettings(self): s = QSettings() s.setValue("strip_trailing_whitespace", self.stripwsp.isChecked()) s.setValue("backup_keep", self.backup.isChecked()) s.setValue("metainfo", self.metainfo.isChecked()) s.setValue("basedir", self.basedir.path())
class Running(preferences.Group): def __init__(self, page): super(Running, self).__init__(page) layout = QVBoxLayout() self.setLayout(layout) self.saveDocument = QCheckBox(clicked=self.changed) self.deleteFiles = QCheckBox(clicked=self.changed) self.noTranslation = QCheckBox(clicked=self.changed) self.includeLabel = QLabel() self.include = widgets.listedit.FilePathEdit() self.include.listBox.setDragDropMode(QAbstractItemView.InternalMove) self.include.changed.connect(self.changed) layout.addWidget(self.saveDocument) layout.addWidget(self.deleteFiles) layout.addWidget(self.noTranslation) layout.addWidget(self.includeLabel) layout.addWidget(self.include) app.translateUI(self) def translateUI(self): self.setTitle(_("Running LilyPond")) self.saveDocument.setText(_("Save document if possible")) self.saveDocument.setToolTip( _("If checked, the document is saved when it is local and modified.\n" "Otherwise a temporary file is used to run LilyPond.")) self.deleteFiles.setText(_("Delete intermediate output files")) self.deleteFiles.setToolTip( _("If checked, LilyPond will delete intermediate PostScript files." )) self.noTranslation.setText(_("Run LilyPond with English messages")) self.noTranslation.setToolTip( _("If checked, LilyPond's output messages will be in English.\n" "This can be useful for bug reports.")) self.includeLabel.setText(_("LilyPond include path:")) def loadSettings(self): s = settings() self.saveDocument.setChecked(s.value("save_on_run", False, bool)) self.deleteFiles.setChecked( s.value("delete_intermediate_files", True, bool)) self.noTranslation.setChecked(s.value("no_translation", False, bool)) include_path = qsettings.get_string_list(s, "include_path") self.include.setValue(include_path) def saveSettings(self): s = settings() s.setValue("save_on_run", self.saveDocument.isChecked()) s.setValue("delete_intermediate_files", self.deleteFiles.isChecked()) s.setValue("no_translation", self.noTranslation.isChecked()) s.setValue("include_path", self.include.value())
class FontLayout(QGridLayout): """Font selection""" def __init__(self, value, parent=None): QGridLayout.__init__(self) font = tuple_to_qfont(value) assert font is not None # Font family self.family = QFontComboBox(parent) self.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.addWidget(self.size, 1, 0) # Italic or not self.italic = QCheckBox(self.tr("Italic"), parent) self.addWidget(self.italic, 1, 1) # Bold or not self.bold = QCheckBox(self.tr("Bold"), parent) self.addWidget(self.bold, 1, 2) self.set_font(font) def set_font(self, font): self.family.setCurrentFont(font) size = font.pointSize() i = self.size.findText(str(size)) if i >= 0: self.size.setCurrentIndex(i) self.italic.setChecked(font.italic()) self.bold.setChecked(font.bold()) def get_font(self): font = self.family.currentFont() font.setItalic(self.italic.isChecked()) font.setBold(self.bold.isChecked()) font.setPointSize(int(self.size.currentText())) return qfont_to_tuple(font)
class ExperimentalFeatures(preferences.Group): def __init__(self, page): super(ExperimentalFeatures, self).__init__(page) layout = QVBoxLayout() self.setLayout(layout) self.experimentalFeatures = QCheckBox(toggled=self.changed) layout.addWidget(self.experimentalFeatures) app.translateUI(self) def translateUI(self): self.setTitle(_("Experimental Features")) self.experimentalFeatures.setText(_("Enable Experimental Features")) self.experimentalFeatures.setToolTip('<qt>' + _( "If checked, features that are not yet finished are enabled.\n" "You need to restart Frescobaldi to see the changes.")) def loadSettings(self): s = QSettings() self.experimentalFeatures.setChecked(s.value("experimental-features", False, bool)) def saveSettings(self): s = QSettings() s.setValue("experimental-features", self.experimentalFeatures.isChecked())
class Prefs(preferences.Group): def __init__(self, page): super(Prefs, self).__init__(page) self._closeOutputs = QCheckBox(clicked=self.changed) self._pollingLabel = QLabel() self._pollingTime = QSpinBox() self._pollingTime.setRange(0, 1000) self._pollingTime.setSuffix(" ms") self._pollingTime.valueChanged.connect(self.changed) layout = QVBoxLayout() self.setLayout(layout) layout.addWidget(self._closeOutputs) app.translateUI(self) hbox = QHBoxLayout() layout.addLayout(hbox) hbox.addWidget(self._pollingLabel) hbox.addWidget(self._pollingTime) def translateUI(self): self.setTitle(_("Preferences")) self._closeOutputs.setText(_("Close unused MIDI output")) self._closeOutputs.setToolTip( _("Closes unused MIDI ports after one minute. " 'See "What\'s This" for more information.') ) self._closeOutputs.setWhatsThis( _( "<p>If checked, Frescobaldi will close MIDI output ports that are not " "used for one minute.</p>\n" "<p>This could free up system resources that a software MIDI synthesizer " "might be using, thus saving battery power.</p>\n" "<p>A side effect is that if you pause a MIDI file for a long time " "the instruments are reset to the default piano (instrument 0). " "In that case, playing the file from the beginning sets up the " "instruments again.</p>\n" ) ) self._pollingLabel.setText(_("Polling time for input:")) self._pollingTime.setToolTip(_("Polling time for MIDI input. " 'See "What\'s This" for more information.')) self._pollingTime.setWhatsThis( _( "Sets the time between the polling of the MIDI input port in milliseconds. " "Small values lead to faster recognition of incoming MIDI events, but stress " "the CPU. 10 ms should be a good value." ) ) def loadSettings(self): s = QSettings() self._closeOutputs.setChecked(s.value("midi/close_outputs", False, bool)) self._pollingTime.setValue(s.value("midi/polling_time", 10, int)) def saveSettings(self): s = QSettings() s.setValue("midi/close_outputs", self._closeOutputs.isChecked()) s.setValue("midi/polling_time", self._pollingTime.value())
class ViewSettings(preferences.Group): def __init__(self, page): super(ViewSettings, self).__init__(page) layout = QVBoxLayout() self.setLayout(layout) self.wrapLines = QCheckBox(toggled=self.changed) layout.addWidget(self.wrapLines) app.translateUI(self) def translateUI(self): self.setTitle(_("View Preferences")) self.wrapLines.setText(_("Wrap long lines by default")) self.wrapLines.setToolTip('<qt>' + _( "If enabled, lines that don't fit in the editor width are wrapped " "by default. " "Note: when the document is displayed by multiple views, they all " "share the same line wrapping width, which might look strange.")) def loadSettings(self): s = QSettings() s.beginGroup("view_preferences") self.wrapLines.setChecked(s.value("wrap_lines", False, bool)) def saveSettings(self): s = QSettings() s.beginGroup("view_preferences") s.setValue("wrap_lines", self.wrapLines.isChecked())
class BooleanParameterWidget(GenericParameterWidget): """Widget class for boolean parameter.""" def __init__(self, parameter, parent=None): """Constructor .. versionadded:: 2.2 :param parameter: A BooleanParameter object. :type parameter: BooleanParameter """ super(BooleanParameterWidget, self).__init__(parameter, parent) # Get the parameter label and use its value as the checkbox text label_item = self._input_layout.itemAt(0) label_widget = label_item.widget() text = label_widget.text() self._check_box_input = QCheckBox(text) # Tooltips self.setToolTip('Tick here to enable ' + self._parameter.name) self._check_box_input.setChecked(self._parameter.value) self._inner_input_layout.insertWidget(0, self._check_box_input) self._input_layout.removeItem(label_item) def get_parameter(self): """Obtain boolean parameter object from the current widget state. :returns: A BooleanParameter from the current state of widget """ self._parameter.value = self._check_box_input.isChecked() return self._parameter
class CheckBox(QWidget): status_changed = pyqtSignal(bool) def __init__(self, caption, checked=False, tooltip=""): QWidget.__init__(self) self.value = checked self.checkbox = QCheckBox(caption) self.checkbox.stateChanged.connect(self.__on_change) self.checkbox.setToolTip(tooltip) hbox = QHBoxLayout() hbox.addWidget(self.checkbox) hbox.setMargin(0) self.setLayout(hbox) # self.setContentsMargins(5, 0, 5, 0) self.setContentsMargins(0, 0, 0, 0) self.checkbox.setChecked(self.value) def __on_change(self, value): self.value = value if value == Qt.Unchecked: self.status_changed.emit(False) else: self.status_changed.emit(True) def get_value(self): return self.checkbox.isChecked()
class DummyConfigWidget(QWidget, config.ConfigurationWidgetMixin): NAME_PREFIX = 'dummy' PROPERTY_MAP = dict(QCheckBox='checked', QLineEdit='text') CHANGED_SIGNAL_MAP = dict(QCheckBox='toggled', QLineEdit='textChanged') configurationChanged = pyqtSignal(bool) def __init__(self, config, parent=None): QWidget.__init__(self, parent) layout = QHBoxLayout(self) self.setLayout(layout) self.checkbox = QCheckBox(self) self.checkbox.setObjectName('dummy_checkbox') layout.addWidget(self.checkbox) self.lineedit = QLineEdit(self) self.lineedit.setObjectName('dummy_lineedit') layout.addWidget(self.lineedit) self._setup(config) def change(self, text, check_state): self.lineedit.setText(text) self.checkbox.setChecked(check_state) def check(self, text, check_state): __tracebackhide__ = True assert unicode(self.lineedit.text()) == text assert self.checkbox.isChecked() == check_state
def test_should_return_uncheckedvalue_on_false(): checkbox = QCheckBox() widget = CheckboxWidget(widget=checkbox) widget.config = config widget.setvalue('MyFalse') assert checkbox.isChecked() == False assert widget.value() == 'MyFalse'
class DummyConfigWidget(QWidget, config.ConfigurationWidgetMixin): NAME_PREFIX = 'dummy' PROPERTY_MAP = dict(QCheckBox='checked', QLineEdit='text') CHANGED_SIGNAL_MAP = dict(QCheckBox='toggled', QLineEdit='textChanged') configurationChanged = pyqtSignal(bool) def __init__(self, config, parent=None): QWidget.__init__(self, parent) layout = QHBoxLayout(self) self.setLayout(layout) self.checkbox = QCheckBox(self) self.checkbox.setObjectName('dummy_checkbox') layout.addWidget(self.checkbox) self.lineedit = QLineEdit(self) self.lineedit.setObjectName('dummy_lineedit') layout.addWidget(self.lineedit) self._setup(config) def change(self, text, check_state): self.lineedit.setText(text) self.checkbox.setChecked(check_state) def check(self, text, check_state): __tracebackhide__ = True assert unicode(self.lineedit.text()) == text assert self.checkbox.isChecked() == check_state
class PianoStaff(StaffBase): def __init__(self, dialog): StaffBase.__init__(self, dialog) l = QLabel(i18n("Systems per page:")) l.setBuddy(self.systems) self.layout().addWidget(l, 0, 1, Qt.AlignRight) self.layout().addWidget(self.systems, 0, 2) self.clefs = QCheckBox(i18n("Clefs")) self.layout().addWidget(self.clefs, 1, 2) def name(self): return i18n("Piano Staff") def default(self): self.systems.setValue(6) self.clefs.setChecked(True) def music(self, layout): layout.setSpanBarContexts(['PianoStaff']) if not self.clefs.isChecked(): layout.add('Staff', "\\override Clef #'transparent = ##t") if lilyPondVersion() < (2, 13, 4): spacing = "#'minimum-Y-extent = #'(-6 . 3)" elif lilyPondVersion() < (2, 14, 0): spacing = "#'next-staff-spacing = #'((space . 10))" else: spacing = "#'next-staff-spacing = #'((basic-distance . 10))" return ['\\new PianoStaff <<', '\\new Staff \\with {', '\\override VerticalAxisGroup ' + spacing, '} { \\clef treble \\music }', '\\new Staff { \\clef bass \\music }', '>>']
def test_should_return_uncheckedvalue_on_false(): checkbox = QCheckBox() widget = CheckboxWidget(widget=checkbox) widget.config = config widget.setvalue('MyFalse') assert checkbox.isChecked() == False assert widget.value() == 'MyFalse'
class ExperimentalFeatures(preferences.Group): def __init__(self, page): super(ExperimentalFeatures, self).__init__(page) layout = QVBoxLayout() self.setLayout(layout) self.experimentalFeatures = QCheckBox(toggled=self.changed) layout.addWidget(self.experimentalFeatures) app.translateUI(self) def translateUI(self): self.setTitle(_("Experimental Features")) self.experimentalFeatures.setText(_("Enable Experimental Features")) self.experimentalFeatures.setToolTip( '<qt>' + _("If checked, features that are not yet finished are enabled.\n" "You need to restart Frescobaldi to see the changes.")) def loadSettings(self): s = QSettings() self.experimentalFeatures.setChecked( s.value("experimental-features", False, bool)) def saveSettings(self): s = QSettings() s.setValue("experimental-features", self.experimentalFeatures.isChecked())
class BooleanParameterWidget(GenericParameterWidget): """Widget class for boolean parameter.""" def __init__(self, parameter, parent=None): """Constructor .. versionadded:: 2.2 :param parameter: A BooleanParameter object. :type parameter: BooleanParameter """ super(BooleanParameterWidget, self).__init__(parameter, parent) self._check_box_input = QCheckBox() # Tooltips self.setToolTip('Tick here to enable ' + self._parameter.name) self._check_box_input.setChecked(self._parameter.value) self._inner_input_layout.addWidget(self._check_box_input) def get_parameter(self): """Obtain boolean parameter object from the current widget state. :returns: A BooleanParameter from the current state of widget """ self._parameter.value = self._check_box_input.isChecked() return self._parameter
class BooleanParameterWidget(GenericParameterWidget): """Widget class for boolean parameter.""" def __init__(self, parameter, parent=None): """Constructor .. versionadded:: 2.2 :param parameter: A BooleanParameter object. :type parameter: BooleanParameter """ super(BooleanParameterWidget, self).__init__(parameter, parent) # Get the parameter label and use its value as the checkbox text label_item = self.input_layout.itemAt(0) label_widget = label_item.widget() text = label_widget.text() self._check_box_input = QCheckBox(text) # Tooltips self.setToolTip('Tick here to enable ' + self._parameter.name) self._check_box_input.setChecked(self._parameter.value) self.inner_input_layout.insertWidget(0, self._check_box_input) self.input_layout.removeItem(label_item) def get_parameter(self): """Obtain boolean parameter object from the current widget state. :returns: A BooleanParameter from the current state of widget """ self._parameter.value = self._check_box_input.isChecked() return self._parameter
class Banjo(TablaturePart): @staticmethod def title(_=__builtin__._): return _("Banjo") @staticmethod def short(_=__builtin__._): return _("abbreviation for Banjo", "Bj.") midiInstrument = "banjo" tabFormat = "fret-number-tablature-format-banjo" tunings = ( ("banjo-open-g-tuning", lambda: _("Open G-tuning (aDGBD)")), ("banjo-c-tuning", lambda: _("C-tuning (gCGBD)")), ("banjo-modal-tuning", lambda: _("Modal tuning (gDGCD)")), ("banjo-open-d-tuning", lambda: _("Open D-tuning (aDF#AD)")), ("banjo-open-dm-tuning", lambda: _("Open Dm-tuning (aDFAD)")), ) def createTuningWidgets(self, layout): super(Banjo, self).createTuningWidgets(layout) self.fourStrings = QCheckBox() layout.addWidget(self.fourStrings) def translateTuningWidgets(self): super(Banjo, self).translateTuningWidgets() self.fourStrings.setText(_("Four strings (instead of five)")) def setTunings(self, tab): if not self.fourStrings.isChecked(): super(Banjo, self).setTunings(tab) else: tab.getWith()["stringTunings"] = ly.dom.Scheme( "(four-string-banjo {0})".format(self.tunings[self.tuning.currentIndex()][0]) )
class ViewSettings(preferences.Group): def __init__(self, page): super(ViewSettings, self).__init__(page) layout = QVBoxLayout() self.setLayout(layout) self.wrapLines = QCheckBox(toggled=self.changed) layout.addWidget(self.wrapLines) app.translateUI(self) def translateUI(self): self.setTitle(_("View Preferences")) self.wrapLines.setText(_("Wrap long lines by default")) self.wrapLines.setToolTip('<qt>' + _( "If enabled, lines that don't fit in the editor width are wrapped " "by default. " "Note: when the document is displayed by multiple views, they all " "share the same line wrapping width, which might look strange.")) def loadSettings(self): s = QSettings() s.beginGroup("view_preferences") self.wrapLines.setChecked(s.value("wrap_lines", False, bool)) def saveSettings(self): s = QSettings() s.beginGroup("view_preferences") s.setValue("wrap_lines", self.wrapLines.isChecked())
class CheckBox(QWidget): status_changed = pyqtSignal(bool) def __init__(self, caption, checked=False, tooltip=''): QWidget.__init__(self) self.value = checked self.checkbox = QCheckBox(caption) self.checkbox.stateChanged.connect(self.__on_change) self.checkbox.setToolTip(tooltip) hbox = QHBoxLayout() hbox.addWidget(self.checkbox) hbox.setMargin(0) self.setLayout(hbox) #self.setContentsMargins(5, 0, 5, 0) self.setContentsMargins(0, 0, 0, 0) self.checkbox.setChecked(self.value) def __on_change(self, value): self.value = value if value == Qt.Unchecked: self.status_changed.emit(False) else: self.status_changed.emit(True) def get_value(self): return self.checkbox.isChecked()
class BooleanParameterWidget(GenericParameterWidget): """Widget class for boolean parameter.""" def __init__(self, parameter, parent=None): """Constructor .. versionadded:: 2.2 :param parameter: A BooleanParameter object. :type parameter: BooleanParameter """ super(BooleanParameterWidget, self).__init__(parameter, parent) self._check_box_input = QCheckBox() # Tooltips self.setToolTip('Tick here to enable ' + self._parameter.name) self._check_box_input.setChecked(self._parameter.value) self._inner_input_layout.addWidget(self._check_box_input) def get_parameter(self): """Obtain boolean parameter object from the current widget state. :returns: A BooleanParameter from the current state of widget """ self._parameter.value = self._check_box_input.isChecked() return self._parameter
def simple_dialog(parent, title, message, checkbox_text=None, yes_no=True): """ A simple dialog the enable you show an html message with checkbox. :param parent: The parent of the dialog. :type parent: QWidget :param title: The title of the dialog :type title: String :param message: The message of the dialog. Use <br> to add a new line as it is html. :type message: String :param checkbox_text: Add a checkbox text, if None, the checkbox will not be shown. :type checkbox_text: String :param yes_no: A boolean to add the Yes No buttons. If false, the Ok button is shown. :type yes_no: Boolean :return: Tuple containing the dialog exec_ result and the checkbox result. :rtype: Tuple """ simple_dialog = QDialog( parent, Qt.WindowSystemMenuHint | Qt.WindowTitleHint ) simple_layout = QVBoxLayout(simple_dialog) simple_label = QLabel() simple_dialog.setWindowTitle(title) simple_label.setTextFormat(Qt.RichText) simple_label.setText(message) simple_layout.addWidget(simple_label) if checkbox_text: confirm_checkbox = QCheckBox() confirm_checkbox.setText(checkbox_text) simple_layout.addWidget(confirm_checkbox) simple_buttons = QDialogButtonBox() if yes_no: simple_buttons.setStandardButtons( QDialogButtonBox.Yes | QDialogButtonBox.No ) simple_buttons.rejected.connect(simple_dialog.reject) else: simple_buttons.setStandardButtons( QDialogButtonBox.Ok ) simple_buttons.accepted.connect(simple_dialog.accept) simple_layout.addWidget(simple_buttons) simple_dialog.setModal(True) result = simple_dialog.exec_() if not checkbox_text is None: return result, confirm_checkbox.isChecked() else: return result, False
class FontLayout(QGridLayout): """Font selection""" def __init__(self, value, parent=None): QGridLayout.__init__(self) font = tuple_to_qfont(value) assert font is not None # Font family self.family = QFontComboBox(parent) self.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.addWidget(self.size, 1, 0) # Italic or not self.italic = QCheckBox(self.tr("Italic"), parent) self.addWidget(self.italic, 1, 1) # Bold or not self.bold = QCheckBox(self.tr("Bold"), parent) self.addWidget(self.bold, 1, 2) self.set_font(font) def set_font(self, font): self.family.setCurrentFont(font) size = font.pointSize() i = self.size.findText(str(size)) if i >= 0: self.size.setCurrentIndex(i) self.italic.setChecked(font.italic()) self.bold.setChecked(font.bold()) def get_font(self): font = self.family.currentFont() font.setItalic(self.italic.isChecked()) font.setBold(self.bold.isChecked()) font.setPointSize(int(self.size.currentText())) return qfont_to_tuple(font)
class UpdateOptionsWidget(QWidget): """ A Widget with download/update/remove options. """ #: Install/update button was clicked installClicked = Signal() #: Remove button was clicked. removeClicked = Signal() def __init__(self, state=AVAILABLE, parent=None): QWidget.__init__(self, parent) layout = QHBoxLayout() layout.setSpacing(1) layout.setContentsMargins(1, 1, 1, 1) self.checkButton = QCheckBox() layout.addWidget(self.checkButton) self.setLayout(layout) self.setMinimumHeight(20) self.setMaximumHeight(20) self.state = -1 self.setState(state) def setState(self, state): """ Set the current update state for the widget (AVAILABLE, CURRENT, OUTDATED or DEPRECTED). """ self.state = state self._update() def _update(self): if self.state == AVAILABLE: self.checkButton.setChecked(False) elif self.state == CURRENT: self.checkButton.setChecked(True) elif self.state == OUTDATED: self.checkButton.setChecked(True) elif self.state == DEPRECATED: self.checkButton.setChecked(True) else: raise ValueError("Invalid state %r" % self._state) try: self.checkButton.clicked.disconnect( ) # Remove old signals if they exist except Exception: pass if not self.checkButton.isChecked( ): # Switch signals if the file is present or not self.checkButton.clicked.connect(self.installClicked) else: self.checkButton.clicked.connect(self.removeClicked)
class Prefs(preferences.Group): def __init__(self, page): super(Prefs, self).__init__(page) self._closeOutputs = QCheckBox(clicked=self.changed) self._pollingLabel = QLabel() self._pollingTime = QSpinBox() self._pollingTime.setRange(0, 1000) self._pollingTime.setSuffix(" ms") self._pollingTime.valueChanged.connect(self.changed) layout = QVBoxLayout() self.setLayout(layout) layout.addWidget(self._closeOutputs) app.translateUI(self) hbox = QHBoxLayout() layout.addLayout(hbox) hbox.addWidget(self._pollingLabel) hbox.addWidget(self._pollingTime) def translateUI(self): self.setTitle(_("Preferences")) self._closeOutputs.setText(_("Close unused MIDI output")) self._closeOutputs.setToolTip( _("Closes unused MIDI ports after one minute. " "See \"What's This\" for more information.")) self._closeOutputs.setWhatsThis( _("<p>If checked, Frescobaldi will close MIDI output ports that are not " "used for one minute.</p>\n" "<p>This could free up system resources that a software MIDI synthesizer " "might be using, thus saving battery power.</p>\n" "<p>A side effect is that if you pause a MIDI file for a long time " "the instruments are reset to the default piano (instrument 0). " "In that case, playing the file from the beginning sets up the " "instruments again.</p>\n")) self._pollingLabel.setText(_("Polling time for input:")) self._pollingTime.setToolTip( _("Polling time for MIDI input. " "See \"What's This\" for more information.")) self._pollingTime.setWhatsThis( _("Sets the time between the polling of the MIDI input port in milliseconds. " "Small values lead to faster recognition of incoming MIDI events, but stress " "the CPU. 10 ms should be a good value.")) def loadSettings(self): s = QSettings() self._closeOutputs.setChecked( s.value("midi/close_outputs", False, bool)) self._pollingTime.setValue(s.value("midi/polling_time", 10, int)) def saveSettings(self): s = QSettings() s.setValue("midi/close_outputs", self._closeOutputs.isChecked()) s.setValue("midi/polling_time", self._pollingTime.value())
class LilyPondVersions(SettingsGroup): """Manage multiple versions of LilyPond.""" def __init__(self, page): super(LilyPondVersions, self).__init__(i18n("LilyPond versions to use:"), page) layout = QVBoxLayout(self) self.instances = LilyPondInfoList(self) self.instances.changed.connect(page.changed) layout.addWidget(self.instances) self.auto = QCheckBox( i18n("Enable automatic version selection " "(choose LilyPond version from document)"), clicked=page.changed ) layout.addWidget(self.auto) def defaults(self): """ Reset ourselves to default state. """ self.instances.clear() info = self.instances.createItem() self.instances.addItem(info) self.instances.setCurrentItem(info) self.auto.setChecked(False) def loadSettings(self): self.instances.clear() conf = config("lilypond") self.auto.setChecked(conf.readEntry("automatic version", False)) paths = conf.readEntry("paths", ["lilypond"]) default = conf.readEntry("default", "lilypond") # sort on version and move erratic entries to the end paths.sort(key=lambda path: ly.version.LilyPondInstance(path).version() or (999,)) for path in paths: info = LilyPondInfoItem(path) info.loadSettings(conf.group(path)) info.default = path == default self.instances.addItem(info) if info.default: self.instances.setCurrentItem(info) def saveSettings(self): paths = [] default = "" conf = config("lilypond") conf.deleteGroup() for info in self.instances.items(): paths.append(info.lilypond) if info.default: default = info.lilypond info.saveSettings(conf.group(info.lilypond)) if not paths: paths = ["lilypond"] if not default: default = paths[0] conf.writeEntry("paths", paths) conf.writeEntry("default", default) conf.writeEntry("automatic version", self.auto.isChecked())
class UpdateOptionsWidget(QWidget): """ A Widget with download/update/remove options. """ #: Install/update button was clicked installClicked = Signal() #: Remove button was clicked. removeClicked = Signal() def __init__(self, state=AVAILABLE, parent=None): QWidget.__init__(self, parent) layout = QHBoxLayout() layout.setSpacing(1) layout.setContentsMargins(1, 1, 1, 1) self.checkButton = QCheckBox() layout.addWidget(self.checkButton) self.setLayout(layout) self.setMinimumHeight(20) self.setMaximumHeight(20) self.state = -1 self.setState(state) def setState(self, state): """ Set the current update state for the widget (AVAILABLE, CURRENT, OUTDATED or DEPRECTED). """ self.state = state self._update() def _update(self): if self.state == AVAILABLE: self.checkButton.setChecked(False) elif self.state == CURRENT: self.checkButton.setChecked(True) elif self.state == OUTDATED: self.checkButton.setChecked(True) elif self.state == DEPRECATED: self.checkButton.setChecked(True) else: raise ValueError("Invalid state %r" % self._state) try: self.checkButton.clicked.disconnect() # Remove old signals if they exist except Exception: pass if not self.checkButton.isChecked(): # Switch signals if the file is present or not self.checkButton.clicked.connect(self.installClicked) else: self.checkButton.clicked.connect(self.removeClicked)
class LancerDes(MyMiniFrame): def __init__(self, parent): MyMiniFrame.__init__(self, parent, u"Simulation de lancers de dés") self.parent = parent sizer = QVBoxLayout() sizer.addWidget(QLabel(u"On simule le lancer d'un ou plusieurs dés")) sizer.addWidget(QLabel(u"à 6 faces, et on étudie la somme des points.")) exp = QHBoxLayout() exp.addWidget(QLabel(u"Nombre de dés:")) ex = self.experience = QSpinBox() ex.setRange(1, 100000) ex.setValue(1) ex.valueChanged.connect(self.actualiser) exp.addWidget(self.experience) sizer.addLayout(exp) nbr = QHBoxLayout() nbr.addWidget(QLabel(u"Nombre de lancers:")) sc = self.sc = QSpinBox() sc.setRange(1, 100000) sc.setValue(1) self.sc.valueChanged.connect(self.actualiser) nbr.addWidget(sc) sizer.addLayout(nbr) self.cb = QCheckBox(u"Conserver les valeurs") sizer.addWidget(self.cb) boutons = QHBoxLayout() fermer = QPushButton(u"Fermer") boutons.addWidget(fermer) lancer = QPushButton(u"Lancer l'expérience") boutons.addWidget(lancer) fermer.clicked.connect(self.close) lancer.clicked.connect(self.actualiser) sizer.addLayout(boutons) self.setLayout(sizer) def actualiser(self, event = None): if not self.cb.isChecked(): self.parent.actualiser(False) self.parent.graph = 'batons' n = self.sc.value() des = self.experience.value() for val in range(des, 6*des + 1): self.parent.ajouter_valeur(val, 0) self.parent.ajouter_valeurs(*[de(des) for i in xrange(n)]) self.parent.calculer() self.parent.legende_x = u"points obtenus" self.parent.legende_y = u"nombre de lancers" self.parent.affiche()
class AutoNumbering(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) def hbox(*widgets): box = QHBoxLayout() [box.addWidget(z) for z in widgets] box.addStretch() return box vbox = QVBoxLayout() startlabel = QLabel(translate('Autonumbering Wizard', "&Start: ")) self._start = QSpinBox() startlabel.setBuddy(self._start) self._start.setValue(1) self._start.setMaximum(65536) vbox.addLayout(hbox(startlabel, self._start)) label = QLabel( translate('Autonumbering Wizard', 'Max length after padding with zeroes: ')) self._padlength = QSpinBox() label.setBuddy(self._padlength) self._padlength.setValue(1) self._padlength.setMaximum(65535) self._padlength.setMinimum(1) vbox.addLayout(hbox(label, self._padlength)) self._restart_numbering = QCheckBox( translate('Autonumbering Wizard', "&Restart numbering at each directory.")) vbox.addWidget(self._restart_numbering) vbox.addStretch() self.setLayout(vbox) def setArguments(self, *args): minimum = sanitize(int, args[0], 0) restart = sanitize(bool, args[1], True) padding = sanitize(int, args[2], 1) self._start.setValue(minimum) self._restart_numbering.setChecked(restart) self._padlength.setValue(padding) def arguments(self): x = [ self._start.value(), self._restart_numbering.isChecked(), self._padlength.value() ] return x
class StaffGroup(_base.Container): @staticmethod def title(_=_base.translate): return _("Staff Group") def accepts(self): return (StaffGroup, _base.Part) def createWidgets(self, layout): self.systemStartLabel = QLabel() self.systemStart = QComboBox() self.systemStartLabel.setBuddy(self.systemStart) self.systemStart.setModel( listmodel.ListModel( ( # L10N: Brace like a piano staff (lambda: _("Brace"), 'system_start_brace'), # L10N: Bracket like a choir staff (lambda: _("Bracket"), 'system_start_bracket'), # L10N: Square bracket like a sub-group (lambda: _("Square"), 'system_start_square'), ), self.systemStart, display=listmodel.translate_index(0), icon=lambda item: symbols.icon(item[1]))) self.systemStart.setIconSize(QSize(64, 64)) self.connectBarLines = QCheckBox(checked=True) box = QHBoxLayout() box.addWidget(self.systemStartLabel) box.addWidget(self.systemStart) layout.addLayout(box) layout.addWidget(self.connectBarLines) def translateWidgets(self): self.systemStartLabel.setText(_("Type:")) self.connectBarLines.setText(_("Connect Barlines")) self.connectBarLines.setToolTip( _("If checked, barlines are connected between the staves.")) self.systemStart.model().update() def build(self, data, builder): s = self.systemStart.currentIndex() b = self.connectBarLines.isChecked() if s == 0: node = ly.dom.GrandStaff() if not b: ly.dom.Line("\\remove Span_bar_engraver", node.getWith()) else: node = ly.dom.StaffGroup() if b else ly.dom.ChoirStaff() if s == 2: node.getWith()['systemStartDelimiter'] = ly.dom.Scheme( "'SystemStartSquare") data.nodes.append(node) data.music = ly.dom.Simr(node)
class FkFilter(QWidget): """Handle filtering of a list by matching foreign keys of the input.""" filter_changed = pyqtSignal() def __init__(self, meta): """Create qt widget and attach handlers.""" QWidget.__init__(self) self.meta = meta hbox = QHBoxLayout() hbox.setContentsMargins(0, 0, 0, 0) self.checkbox = QCheckBox() self.edit = QLineEdit() self.label = QLabel('Fk Filter:') hbox.addWidget(self.checkbox) hbox.addWidget(self.label) hbox.addWidget(self.edit) self.setLayout(hbox) self.checkbox.setChecked(True) # self.checkbox.setTristate(True) # when the text is changed, run the filter self.edit.textChanged.connect(self.filter_changed) self.edit.textChanged.connect(self.reset) self.checkbox.stateChanged.connect(self.filter_changed) def reset(self): if hasattr(self, '_fks'): del self._fks self.filter_changed.emit() def filter_item(self, list_item): """Filter an item if it isn't a foreign key of the input.""" if self.checkbox.isChecked(): return str(list_item) not in self.fks() else: return False def fks(self): if not hasattr(self, '_fks'): name = str(self.edit.text()) table = self.meta.tables.get(name) if table is not None: connects_to = (fk.column.table.name for fk in table.foreign_keys) connected_to = (t.name for t in self.meta.tables.itervalues() for fk in t.foreign_keys if fk.column.table is table) fks = set() fks.update(connects_to) fks.update(connected_to) self._fks = fks else: self._fks = set(self.meta.tables.keys()) return self._fks
class Dialog(toly_dialog.ToLyDialog): def __init__(self, parent=None): self.imp_prgm = "midi2ly" self.userg = "midi_import" self.useAbsCheck = QCheckBox() self.impChecks = [self.useAbsCheck] self.useAbsCheck.setObjectName("absolute-mode") self.impExtra = [] super(Dialog, self).__init__(parent) app.translateUI(self) qutil.saveDialogSize(self, "midi_import/dialog/size", QSize(480, 260)) self.makeCommandLine() self.loadSettings() def translateUI(self): self.useAbsCheck.setText(_("Pitches in absolute mode")) self.buttons.button(QDialogButtonBox.Ok).setText(_("Run midi2ly")) super(Dialog, self).translateUI() def makeCommandLine(self): """Reads the widgets and builds a command line.""" cmd = ["$midi2ly"] if self.useAbsCheck.isChecked(): cmd.append('-a') cmd.append("$filename") self.commandLine.setText(' '.join(cmd)) def loadSettings(self): """Get users previous settings.""" self.imp_default = [False] self.settings = QSettings() self.settings.beginGroup('midi_import') super(Dialog, self).loadSettings() def saveSettings(self): """Save users last settings.""" self.settings = QSettings() self.settings.beginGroup('midi_import') super(Dialog, self).saveSettings()
class FindDialog(QDialog): """This class Provides interface""" def __init__(self, page=None, parent=None): super().__init__(parent) self.findLineEdit = QLineEdit() self.matchCaseCheckBox = QCheckBox("Match &Case") self.wholeWordsCheckBox = QCheckBox("Whole &Words") # findButton = QPushButton("&Find") self.nextButton = QPushButton("&Next") self.previousButton = QPushButton("&Previous") self.document = page.document() # page is a QTextEdit # TODO: add find backward and forward buttons later # lay the dialog out layout = QHBoxLayout() layout.addWidget(self.findLineEdit) layout.addWidget(self.matchCaseCheckBox) layout.addWidget(self.wholeWordsCheckBox) layout.addWidget(self.nextButton) layout.addWidget(self.previousButton) self.setLayout(layout) def findText(self): """displays a find dialog, selects the find pattern if found and changes the cursor position to the end of the search pattern if it is accepted """ textToFind = self.findLineEdit.text( ) # get the search term from the lineEdit if self.document is not None and isinstance(self.document, QTextDocument): self.document.find(textToFind) if self.matchCaseCheckBox.isChecked(): self.document.find(textToFind, 0, QTextDocument.FindCaseSensitively) if self.wholeWordsCheckBox.isChecked(): self.document.find(textToFind, 0, QTextDocument.FindWholeWords)
class ReportExportOptionsDialog(QDialog): def __init__(self, exportContent=False): QDialog.__init__(self) self.setWindowTitle(self.tr("Export options")) self.reportManager = ReportManager() layout = QVBoxLayout() self.extractContentCheckBox = QCheckBox(self.tr("E&xtract content")) if exportContent: self.extractContentCheckBox.setChecked(True) else: self.extractContentCheckBox.setChecked(False) layout.addWidget(self.extractContentCheckBox) directoryPathLayout = QHBoxLayout() pathLabel = QLabel(self.tr("Report extraction path :")) self.pathLineEdit = QLineEdit(self.reportManager.export_path) self.pathLineEdit.setReadOnly(True) pathButton = QPushButton("...") self.connect(pathButton, SIGNAL("clicked()"), self.askPath) directoryPathLayout.addWidget(pathLabel) directoryPathLayout.addWidget(self.pathLineEdit) directoryPathLayout.addWidget(pathButton) layout.addLayout(directoryPathLayout) buttonLayout = QHBoxLayout() self.buttonOk = QPushButton("O&k") self.connect(self.buttonOk, SIGNAL("clicked()"), self.accept) self.buttonCancel = QPushButton("C&ancel") self.connect(self.buttonCancel, SIGNAL("clicked()"), self.reject) buttonLayout.addWidget(self.buttonOk) buttonLayout.addWidget(self.buttonCancel) layout.addLayout(buttonLayout) self.setLayout(layout) def askPath(self): directory = QFileDialog.getExistingDirectory( self, self.tr("Report extraction directory"), self.reportManager.export_path) if len(directory): directory = os.path.join(str(directory.toUtf8()), 'dff-report') self.pathLineEdit.clear() self.pathLineEdit.insert(directory) self.reportManager.setExportPath(directory) def exportContent(self): if self.extractContentCheckBox.isChecked(): return True else: return False
class Dialog(toly_dialog.ToLyDialog): def __init__(self, parent=None): self.imp_prgm = "midi2ly" self.userg = "midi_import" self.useAbsCheck = QCheckBox() self.impChecks = [self.useAbsCheck] self.useAbsCheck.setObjectName("absolute-mode") self.impExtra = [] super(Dialog, self).__init__(parent) app.translateUI(self) qutil.saveDialogSize(self, "midi_import/dialog/size", QSize(480, 260)) self.makeCommandLine() self.loadSettings() def translateUI(self): self.useAbsCheck.setText(_("Pitches in absolute mode")) self.buttons.button(QDialogButtonBox.Ok).setText(_("Run midi2ly")) super(Dialog, self).translateUI() def makeCommandLine(self): """Reads the widgets and builds a command line.""" cmd = ["$midi2ly"] if self.useAbsCheck.isChecked(): cmd.append('-a') cmd.append("$filename") self.commandLine.setText(' '.join(cmd)) def loadSettings(self): """Get users previous settings.""" self.imp_default = [False] self.settings = QSettings() self.settings.beginGroup('midi_import') super(Dialog, self).loadSettings() def saveSettings(self): """Save users last settings.""" self.settings = QSettings() self.settings.beginGroup('midi_import') super(Dialog, self).saveSettings()
class AutoNumbering(QWidget): def __init__(self, parent = None): QWidget.__init__(self, parent) def hbox(*widgets): box = QHBoxLayout() [box.addWidget(z) for z in widgets] box.addStretch() return box vbox = QVBoxLayout() startlabel = QLabel(translate('Autonumbering Wizard', "&Start: ")) self._start = QSpinBox() startlabel.setBuddy(self._start) self._start.setValue(1) self._start.setMaximum(65536) vbox.addLayout(hbox(startlabel, self._start)) label = QLabel(translate('Autonumbering Wizard', 'Max length after padding with zeroes: ')) self._padlength = QSpinBox() label.setBuddy(self._padlength) self._padlength.setValue(1) self._padlength.setMaximum(65535) self._padlength.setMinimum(1) vbox.addLayout(hbox(label, self._padlength)) self._restart_numbering = QCheckBox(translate('Autonumbering Wizard', "&Restart numbering at each directory.")) vbox.addWidget(self._restart_numbering) vbox.addStretch() self.setLayout(vbox) def setArguments(self, *args): minimum = sanitize(int, args[0], 0) restart = sanitize(bool, args[1], True) padding = sanitize(int, args[2], 1) self._start.setValue(minimum) self._restart_numbering.setChecked(restart) self._padlength.setValue(padding) def arguments(self): x = [ self._start.value(), self._restart_numbering.isChecked(), self._padlength.value()] return x
class ConectatePreferences(QWidget): """The preferences for Conectate backend.""" def __init__(self): super(ConectatePreferences, self).__init__() grid = QGridLayout(self) grid.setSpacing(20) grid.setColumnStretch(1, 10) l = QLabel(u"<b>Ingresá tus datos del portal Conectate:</b>") l.setTextFormat(Qt.RichText) grid.addWidget(l, 0, 0, 1, 2) grid.addWidget(QLabel(u"Usuario:"), 1, 0, 2, 1) prv = config.get('user', '') self.user_entry = QLineEdit(prv) self.user_entry.setPlaceholderText(u'Ingresá tu usuario de Conectate') grid.addWidget(self.user_entry, 1, 1, 2, 2) grid.addWidget(QLabel(u"Contraseña:"), 2, 0, 3, 1) prv = config.get('password', '') self.password_entry = QLineEdit(prv) self.password_entry.setEchoMode(QLineEdit.Password) self.password_entry.setPlaceholderText( u'Ingresá tu contraseña de Conectate') grid.addWidget(self.password_entry, 2, 1, 3, 2) self.password_mask = QCheckBox(u'Mostrar contraseña') self.password_mask.stateChanged.connect(self._toggle_password_mask) grid.addWidget(self.password_mask, 3, 1, 4, 2) l = QLabel(u'Si no tenés estos datos, ' u'<a href="{}">registrate aquí</a>'.format(URL_CONECTATE)) l.setAlignment(Qt.AlignRight | Qt.AlignVCenter) l.setTextFormat(Qt.RichText) l.setOpenExternalLinks(True) grid.addWidget(l, 4, 0, 5, 3) def _toggle_password_mask(self): """Toggle the password hiding.""" if self.password_mask.isChecked() is True: self.password_entry.setEchoMode(QLineEdit.Normal) else: self.password_entry.setEchoMode(QLineEdit.Password) def get_config(self): """Return the config for this tab.""" d = {} d['user'] = self.user_entry.text() d['password'] = self.password_entry.text() return d
class ConectatePreferences(QWidget): """The preferences for Conectate backend.""" def __init__(self): super(ConectatePreferences, self).__init__() grid = QGridLayout(self) grid.setSpacing(20) grid.setColumnStretch(1, 10) l = QLabel(u"<b>Ingresá tus datos del portal Conectate:</b>") l.setTextFormat(Qt.RichText) grid.addWidget(l, 0, 0, 1, 2) grid.addWidget(QLabel(u"Usuario:"), 1, 0, 2, 1) prv = config.get('user', '') self.user_entry = QLineEdit(prv) self.user_entry.setPlaceholderText(u'Ingresá tu usuario de Conectate') grid.addWidget(self.user_entry, 1, 1, 2, 2) grid.addWidget(QLabel(u"Contraseña:"), 2, 0, 3, 1) prv = config.get('password', '') self.password_entry = QLineEdit(prv) self.password_entry.setEchoMode(QLineEdit.Password) self.password_entry.setPlaceholderText( u'Ingresá tu contraseña de Conectate') grid.addWidget(self.password_entry, 2, 1, 3, 2) self.password_mask = QCheckBox(u'Mostrar contraseña') self.password_mask.stateChanged.connect(self._toggle_password_mask) grid.addWidget(self.password_mask, 3, 1, 4, 2) l = QLabel(u'Si no tenés estos datos, ' u'<a href="{}">registrate aquí</a>'.format(URL_CONECTATE)) l.setAlignment(Qt.AlignRight | Qt.AlignVCenter) l.setTextFormat(Qt.RichText) l.setOpenExternalLinks(True) grid.addWidget(l, 4, 0, 5, 3) def _toggle_password_mask(self): """Toggle the password hiding.""" if self.password_mask.isChecked() is True: self.password_entry.setEchoMode(QLineEdit.Normal) else: self.password_entry.setEchoMode(QLineEdit.Password) def get_config(self): """Return the config for this tab.""" d = {} d['user'] = self.user_entry.text() d['password'] = self.password_entry.text() return d
class Target(preferences.Group): def __init__(self, page): super(Target, self).__init__(page) layout = QGridLayout() self.setLayout(layout) self.targetPDF = QRadioButton(toggled=page.changed) self.targetSVG = QRadioButton(toggled=page.changed) self.openDefaultView = QCheckBox(clicked=page.changed) layout.addWidget(self.targetPDF, 0, 0) layout.addWidget(self.targetSVG, 0, 1) layout.addWidget(self.openDefaultView, 1, 0, 1, 5) app.translateUI(self) def translateUI(self): self.setTitle(_("Default output format")) self.targetPDF.setText(_("PDF")) self.targetPDF.setToolTip( _("Create PDF (Portable Document Format) documents by default.")) self.targetSVG.setText(_("SVG")) self.targetSVG.setToolTip( _("Create SVG (Scalable Vector Graphics) documents by default.")) self.openDefaultView.setText( _("Open default viewer after successful compile")) self.openDefaultView.setToolTip( _("Shows the PDF or SVG music view when a compile job finishes " "successfully.")) def loadSettings(self): s = settings() target = s.value("default_output_target", "pdf", type("")) if target == "svg": self.targetSVG.setChecked(True) self.targetPDF.setChecked(False) else: self.targetSVG.setChecked(False) self.targetPDF.setChecked(True) self.openDefaultView.setChecked( s.value("open_default_view", True, bool)) def saveSettings(self): s = settings() if self.targetSVG.isChecked(): target = "svg" else: target = "pdf" s.setValue("default_output_target", target) s.setValue("open_default_view", self.openDefaultView.isChecked())
class StaffGroup(_base.Container): @staticmethod def title(_=_base.translate): return _("Staff Group") def accepts(self): return (StaffGroup, _base.Part) def createWidgets(self, layout): self.systemStartLabel = QLabel() self.systemStart = QComboBox() self.systemStartLabel.setBuddy(self.systemStart) self.systemStart.setModel(listmodel.ListModel(( # L10N: Brace like a piano staff (lambda: _("Brace"), 'system_start_brace'), # L10N: Bracket like a choir staff (lambda: _("Bracket"), 'system_start_bracket'), # L10N: Square bracket like a sub-group (lambda: _("Square"), 'system_start_square'), ), self.systemStart, display=listmodel.translate_index(0), icon=lambda item: symbols.icon(item[1]))) self.systemStart.setIconSize(QSize(64, 64)) self.connectBarLines = QCheckBox(checked=True) box = QHBoxLayout() box.addWidget(self.systemStartLabel) box.addWidget(self.systemStart) layout.addLayout(box) layout.addWidget(self.connectBarLines) def translateWidgets(self): self.systemStartLabel.setText(_("Type:")) self.connectBarLines.setText(_("Connect Barlines")) self.connectBarLines.setToolTip(_("If checked, barlines are connected between the staves.")) self.systemStart.model().update() def build(self, data, builder): s = self.systemStart.currentIndex() b = self.connectBarLines.isChecked() if s == 0: node = ly.dom.GrandStaff() if not b: ly.dom.Line("\\remove Span_bar_engraver", node.getWith()) else: node = ly.dom.StaffGroup() if b else ly.dom.ChoirStaff() if s == 2: node.getWith()['systemStartDelimiter'] = ly.dom.Scheme("'SystemStartSquare") data.nodes.append(node) data.music = ly.dom.Simr(node)
class BracketItem(Item): @staticmethod def name(): return i18n("Bracket") @staticmethod def symbol(): return 'system_bracket' def createWidget(self): w = QWidget() w.setLayout(QVBoxLayout()) self.squareBracket = QCheckBox(i18n("Square Bracket")) w.layout().addWidget(self.squareBracket) self.connectBarLines = QCheckBox(i18n("Connect bar lines")) self.connectBarLines.setChecked(True) w.layout().addWidget(self.connectBarLines) return w def music(self, layout): staff = self.connectBarLines.isChecked() and 'StaffGroup' or 'ChoirStaff' layout.addSpanBarContext(staff) withMusic = [] if self.staffCount() == 1: withMusic.append("\override SystemStartBracket #'collapse-height = #1") layout.setAlwaysShowSystemStartBar() if self.squareBracket.isChecked(): withMusic.append("systemStartDelimiter = #'SystemStartSquare") if withMusic: music = ['\\new {0} \\with {{'.format(staff)] + withMusic + ['} <<'] else: music = ['\\new {0} <<'.format(staff)] music.extend(self.childMusic(layout)) music.append('>>') return music
def connect_features(self, source, target): """ Connects the source feature with the target feature. @param source: A QgsPointLocator.Match object. Its foreign key will be updated. A dialog will be opened which asks the user for which foreign key(s) he wants to update. @param target: A QgsPointLocator.Match object. This feature will be used as link target. Its obj_id attribute will be used as primary key. """ dlg = QDialog(self.iface.mainWindow()) dlg.setWindowTitle(self.tr('Select properties to connect')) dlg.setLayout(QFormLayout()) properties = list() for prop in self.network_element_sources[source.layer()]['fields']: cbx = QCheckBox(prop[1]) cbx.setObjectName(prop[0]) properties.append(cbx) dlg.layout().addWidget(cbx) btn_box = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel) dlg.layout().addWidget(btn_box) btn_box.accepted.connect(dlg.accept) btn_box.rejected.connect(dlg.reject) source_feature = self.get_feature_for_match(source) target_feature = self.get_feature_for_match(target) if dlg.exec_(): for cbx in properties: if cbx.isChecked(): source_feature[cbx.objectName()] = target_feature['obj_id'] if source.layer().updateFeature(source_feature): self.iface.messageBar().pushMessage('QGEP', self.tr('Connected {} to {}').format( source_feature[ 'identifier'], target_feature['identifier']), QgsMessageBar.INFO, 5) else: self.iface.messageBar().pushMessage('QGEP', self.tr( 'Error connecting features'), QgsMessageBar.WARNING, 5) self.reset()
def connect_features(self, source, target): """ Connects the source feature with the target feature. @param source: A QgsPointLocator.Match object. Its foreign key will be updated. A dialog will be opened which asks the user for which foreign key(s) he wants to update. @param target: A QgsPointLocator.Match object. This feature will be used as link target. Its obj_id attribute will be used as primary key. """ dlg = QDialog(self.iface.mainWindow()) dlg.setWindowTitle(self.tr('Select properties to connect')) dlg.setLayout(QFormLayout()) properties = list() for prop in self.network_element_sources[source.layer()]: cbx = QCheckBox(prop[1]) cbx.setObjectName(prop[0]) properties.append(cbx) dlg.layout().addWidget(cbx) btn_box = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel) dlg.layout().addWidget(btn_box) btn_box.accepted.connect(dlg.accept) btn_box.rejected.connect(dlg.reject) source_feature = self.get_feature_for_match(source) target_feature = self.get_feature_for_match(target) if dlg.exec_(): for cbx in properties: if cbx.isChecked(): source_feature[cbx.objectName()] = target_feature['obj_id'] if source.layer().updateFeature(source_feature): self.iface.messageBar().pushMessage('QGEP', self.tr('Connected {} to {}').format( source_feature[ 'identifier'], target_feature['identifier']), QgsMessageBar.INFO, 5) else: self.iface.messageBar().pushMessage('QGEP', self.tr( 'Error connecting features'), QgsMessageBar.WARNING, 5) self.reset()
class CheckBox(HelpedWidget): """A checbox widget for booleans. The data structure expected and sent to the getter and setter is a boolean.""" def __init__(self, model, check_label="Do this", help_link="", show_label=True, alt_label=None, default_check_state=True): """Construct a checkbox widget for booleans""" HelpedWidget.__init__(self, check_label, help_link) if show_label: if alt_label != None: self.check = QCheckBox(alt_label, self) else: self.check = QCheckBox(check_label, self) else: self.check = QCheckBox(self) self.check.setTristate(False) self.check.setChecked(default_check_state) self.connect(self.check, QtCore.SIGNAL('stateChanged(int)'), self.contentsChanged) if not show_label: layout = QHBoxLayout() layout.addWidget(self.check) layout.setAlignment(Qt.AlignCenter) layout.setContentsMargins(0, 0, 0, 0) self.addLayout(layout) else: self.addWidget(self.check) assert isinstance(model, BooleanModelMixin) self.model = model self.model.observable().attach( BooleanModelMixin.BOOLEAN_VALUE_CHANGED_EVENT, self.modelChanged) self.modelChanged() def contentsChanged(self): """Called whenever the contents of the checbox changes.""" self.model.setTrue(self.check.isChecked()) def modelChanged(self): """Retrives data from the model and sets the state of the checkbox.""" self.check.setChecked(self.model.isTrue())
class ViewSettings(preferences.Group): def __init__(self, page): super(ViewSettings, self).__init__(page) layout = QGridLayout(spacing=1) self.setLayout(layout) self.wrapLines = QCheckBox(toggled=self.changed) self.numContextLines = QSpinBox(minimum=0, maximum=20, valueChanged=self.changed) self.numContextLinesLabel = l = QLabel() l.setBuddy(self.numContextLines) layout.addWidget(self.wrapLines, 0, 0, 1, 1) layout.addWidget(self.numContextLinesLabel, 1, 0) layout.addWidget(self.numContextLines, 1, 1) app.translateUI(self) def translateUI(self): self.setTitle(_("View Preferences")) self.wrapLines.setText(_("Wrap long lines by default")) self.wrapLines.setToolTip('<qt>' + _( "If enabled, lines that don't fit in the editor width are wrapped " "by default. " "Note: when the document is displayed by multiple views, they all " "share the same line wrapping width, which might look strange.")) self.numContextLinesLabel.setText(_("Number of surrounding lines:")) self.numContextLines.setToolTip('<qt>' + _( "When jumping between search results or clicking on a link, the " "text view tries to scroll as few lines as possible. " "Here you can specify how many surrounding lines at least should " "be visible.")) self.numContextLinesLabel.setToolTip(self.numContextLines.toolTip()) def loadSettings(self): s = QSettings() s.beginGroup("view_preferences") self.wrapLines.setChecked(s.value("wrap_lines", False, bool)) self.numContextLines.setValue(s.value("context_lines", 3, int)) def saveSettings(self): s = QSettings() s.beginGroup("view_preferences") s.setValue("wrap_lines", self.wrapLines.isChecked()) s.setValue("context_lines", self.numContextLines.value())
class IntervalSpinner(QWidget): def __init__(self, parent, min_=1, max_=1000, step=1, round_option=True): QWidget.__init__(self, parent) layout = QVBoxLayout(self) hlayout = QHBoxLayout() self.start = QDoubleSpinBox(self) self.start.setMinimum(min_) self.start.setMaximum(max_) self.end = QDoubleSpinBox(self) self.end.setMinimum(min_) self.end.setMaximum(max_) self.end.setValue(max_) self.start.setSingleStep(step) self.end.setSingleStep(step) self.start.valueChanged.connect(self.on_value_start_changed) self.end.valueChanged.connect(self.on_value_end_changed) hlayout.addWidget(self.start) hlayout.addWidget(self.end) layout.addLayout(hlayout) if round_option: self.integerCheckBox = QCheckBox("Round to integer values", self) layout.addWidget(self.integerCheckBox) def on_value_start_changed(self, val): if self.end.value() < val: self.end.setValue(val) def on_value_end_changed(self, val): if self.start.value() > val: self.start.setValue(val) def getMin(self): return self.start.value() def getMax(self): return self.end.value() def getRound(self): return self.integerCheckBox.isChecked()
class TreeGroupItem(QTreeWidgetItem): groupIcon = QIcon(os.path.join(os.path.dirname(__file__), "icons", "group.gif")) def __init__(self, name, layers, tree): QTreeWidgetItem.__init__(self) self.layers = layers self.name = name self.setText(0, name) self.setIcon(0, self.groupIcon) self.setCheckState(0, Qt.Checked) self.visibleItem = QTreeWidgetItem(self) self.visibleCheck = QCheckBox() self.visibleCheck.setChecked(True) self.visibleItem.setText(0, "Layers visibility") self.addChild(self.visibleItem) tree.setItemWidget(self.visibleItem, 1, self.visibleCheck) @property def visible(self): return self.visibleCheck.isChecked()
class Banjo(TablaturePart): @staticmethod def title(_=_base.translate): return _("Banjo") @staticmethod def short(_=_base.translate): return _("abbreviation for Banjo", "Bj.") midiInstrument = 'banjo' tabFormat = 'fret-number-tablature-format-banjo' tunings = ( ('banjo-open-g-tuning', lambda: _("Open G-tuning (aDGBD)")), ('banjo-c-tuning', lambda: _("C-tuning (gCGBD)")), ('banjo-modal-tuning', lambda: _("Modal tuning (gDGCD)")), ('banjo-open-d-tuning', lambda: _("Open D-tuning (aDF#AD)")), ('banjo-open-dm-tuning', lambda: _("Open Dm-tuning (aDFAD)")), ) def createTuningWidgets(self, layout): super(Banjo, self).createTuningWidgets(layout) self.fourStrings = QCheckBox() layout.addWidget(self.fourStrings) def translateTuningWidgets(self): super(Banjo, self).translateTuningWidgets() self.fourStrings.setText(_("Four strings (instead of five)")) def setTunings(self, tab): i = self.tuning.currentIndex() if i > len(self.tunings) or not self.fourStrings.isChecked(): super(Banjo, self).setTunings(tab) else: tab.getWith()['stringTunings'] = ly.dom.Scheme( '(four-string-banjo {0})'.format(self.tunings[i][0])) def slotCustomTuningEnable(self, index): super(Banjo, self).slotCustomTuningEnable(index) self.fourStrings.setEnabled(index <= len(self.tunings))