class polyRegressionDialog(QtWidgets.QMainWindow): def __init__(self, parent=None): super(polyRegressionDialog, self).__init__(parent) self.title = 'Polynomial Regression' self.left = 50 self.top = 100 self.width = 1200 self.height = 120 self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.setFixedSize(self.size()) self.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.CustomizeWindowHint | QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowStaysOnTopHint) self.featureX = QComboBox(self) self.featureX.setToolTip('Select feature for X axis') self.featureX.move(15, 14) self.featureX.resize(840, 20) label = QLabel('X-Axis Feature', self) label.move(19, 16) label.resize(100, 50) self.featureY = QComboBox(self) self.featureY.setToolTip('Select feature for Y axis') self.featureY.move(15, 60) self.featureY.resize(840, 20) label = QLabel('Y-Axis Feature', self) label.move(19, 62) label.resize(100, 50) descriptions = getDescriptions() self.featureX.setInsertPolicy(QComboBox.NoInsert) self.featureX.setEditable(True) self.featureX.setCompleter(QCompleter(descriptions)) self.featureX.completer().setCompletionMode( QCompleter.UnfilteredPopupCompletion) self.featureY.setInsertPolicy(QComboBox.NoInsert) self.featureY.setEditable(True) self.featureY.setCompleter(QCompleter(descriptions)) self.featureY.completer().setCompletionMode( QCompleter.UnfilteredPopupCompletion) label = QLabel(' Order of\nPolynomial', self) label.move(906, 17) label.resize(120, 75) self.order = QComboBox(self) self.order.setToolTip('Select order of polynomial fit') self.order.move(915, 14) self.order.resize(50, 23) for i in range(1, 10): self.order.addItem(str(i)) plotButton = QPushButton('Plot', self) plotButton.setToolTip('Use button to plot poly regression') plotButton.clicked.connect(self.parent().plotPolyRegression) plotButton.move(1020, 18) plotButton.resize(90, 90)
class ApplicationWindow(QtWidgets.QMainWindow): def __init__(self): QtWidgets.QMainWindow.__init__(self) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.title = 'Linear Regression' self.left = 50 self.top = 100 self.width = 1200 self.height = 120 self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.setFixedSize(self.size()) self.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.CustomizeWindowHint | QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowStaysOnTopHint) self.featureX = QComboBox(self) self.featureX.setToolTip('Select feature for X axis') self.featureX.move(15, 14) self.featureX.resize(840, 20) label = QLabel('X-Axis Feature', self) label.move(19, 20) label.resize(100, 50) self.featureY = QComboBox(self) self.featureY.setToolTip('Select feature for Y axis') self.featureY.move(15, 60) self.featureY.resize(840, 20) label = QLabel('Y-Axis Feature', self) label.move(19, 62) label.resize(100, 50) # descriptions = getDescriptions() # descriptions = [d.lower() for d in descriptions] # descriptions.sort() self.featureX.setInsertPolicy(QComboBox.NoInsert) self.featureX.setEditable(True) self.featureX.setCompleter(QCompleter()) self.featureX.completer().setCompletionMode( QCompleter.UnfilteredPopupCompletion) self.featureY.setInsertPolicy(QComboBox.NoInsert) self.featureY.setEditable(True) self.featureY.setCompleter(QCompleter()) self.featureY.completer().setCompletionMode( QCompleter.UnfilteredPopupCompletion) self.yIntercept = QCheckBox("Y-Intercept", self) self.yIntercept.move(880, 10) self.rSquared = QCheckBox("R^2", self) self.rSquared.move(880, 40) self.slopeCheck = QCheckBox("Slope", self) self.slopeCheck.move(880, 70) plotButton = QPushButton('Plot', self) plotButton.setToolTip('Use button to plot linear regression') # plotButton.clicked.connect(self.parent().plotLinearRegression) plotButton.move(1020, 18) plotButton.resize(90, 90)
def setup_combo_completer(combo_widget: QtWidgets.QComboBox): combo_widget.setEditable(True) combo_widget.setInsertPolicy(QtWidgets.QComboBox.NoInsert) combo_widget.lineEdit().editingFinished.connect( lambda: combo_widget.setCurrentIndex( combo_widget.findText(combo_widget.currentText()))) completer = combo_widget.completer() completer.setCompletionMode(QtWidgets.QCompleter.PopupCompletion) completer.popup().setAlternatingRowColors(True) completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive) completer.setFilterMode(QtCore.Qt.MatchContains)
class Palette_Docker(DockWidget): # Init the docker def __init__(self): super(Palette_Docker, self).__init__() # make base-widget and layout widget = QWidget() layout = QVBoxLayout() buttonLayout = QHBoxLayout() widget.setLayout(layout) self.setWindowTitle(i18n("Python Palette Docker")) # Make a combobox and add palettes self.cmb_palettes = QComboBox() allPalettes = Application.resources("palette") for palette_name in allPalettes: self.cmb_palettes.addItem(palette_name) self.cmb_palettes.model().sort(0) if len(allPalettes.keys()) > 0: self.currentPalette = Palette(allPalettes[list( allPalettes.keys())[0]]) else: self.currentPalette = None self.cmb_palettes.currentTextChanged.connect(self.slot_paletteChanged) layout.addWidget(self.cmb_palettes) # add combobox to the layout self.paletteView = PaletteView() self.paletteView.setPalette(self.currentPalette) layout.addWidget(self.paletteView) self.paletteView.entrySelectedForeGround.connect( self.slot_swatchSelected) self.colorComboBox = QComboBox() self.colorList = list() buttonLayout.addWidget(self.colorComboBox) self.bnSetColor = QToolButton() self.bnSetColor.setText(i18n("Set")) self.bnSetColor.clicked.connect(self.slot_get_color_from_combobox) buttonLayout.addWidget(self.bnSetColor) self.addEntry = QAction(self) self.addEntry.setIconText(i18n("+")) self.addEntry.triggered.connect(self.slot_add_entry) self.addGroup = QAction(self) self.addGroup.triggered.connect(self.slot_add_group) self.addGroup.setText(i18n("Add Group")) self.addGroup.setIconText(str("\U0001F4C2")) self.removeEntry = QAction(self) self.removeEntry.setText(i18n("Remove Entry")) self.removeEntry.setIconText("-") self.removeEntry.triggered.connect(self.slot_remove_entry) addEntryButton = QToolButton() addEntryButton.setDefaultAction(self.addEntry) buttonLayout.addWidget(addEntryButton) addGroupButton = QToolButton() addGroupButton.setDefaultAction(self.addGroup) buttonLayout.addWidget(addGroupButton) removeEntryButton = QToolButton() removeEntryButton.setDefaultAction(self.removeEntry) buttonLayout.addWidget(removeEntryButton) # QActions self.extra = QToolButton() self.editPaletteData = QAction(self) self.editPaletteData.setText(i18n("Edit Palette Settings")) self.editPaletteData.triggered.connect(self.slot_edit_palette_data) self.extra.setDefaultAction(self.editPaletteData) buttonLayout.addWidget(self.extra) self.actionMenu = QMenu() self.exportToGimp = QAction(self) self.exportToGimp.setText(i18n("Export as GIMP Palette File")) self.exportToGimp.triggered.connect(self.slot_export_to_gimp_palette) self.exportToInkscape = QAction(self) self.exportToInkscape.setText( i18n("Export as Inkscape SVG with Swatches")) self.exportToInkscape.triggered.connect( self.slot_export_to_inkscape_svg) self.sortColors = QAction(self) self.sortColors.setText(i18n("Sort Colors")) self.sortColors.triggered.connect(self.slot_sort_colors) self.actionMenu.addAction(self.editPaletteData) self.actionMenu.addAction(self.exportToGimp) self.actionMenu.addAction(self.exportToInkscape) # self.actionMenu.addAction(self.sortColors) self.extra.setMenu(self.actionMenu) layout.addLayout(buttonLayout) self.slot_fill_combobox() self.setWidget(widget) # add widget to the docker def slot_paletteChanged(self, name): allPalettes = Application.resources("palette") if len(allPalettes) > 0 and name in allPalettes: self.currentPalette = Palette( Application.resources("palette")[name]) self.paletteView.setPalette(self.currentPalette) self.slot_fill_combobox() @pyqtSlot('PaletteEntry') def slot_swatchSelected(self, entry): if (self.canvas()) is not None: if (self.canvas().view()) is not None: name = entry.name() if len(entry.id) > 0: name = entry.id() + " - " + entry.name() if len(name) > 0: if name in self.colorList: self.colorComboBox.setCurrentIndex( self.colorList.index(name)) color = self.currentPalette.colorForEntry(entry) self.canvas().view().setForeGroundColor(color) ''' A function for making a combobox with the available colors. We use QCompleter on the colorComboBox so that people can type in the name of a color to select it. This is useful for people with carefully made palettes where the colors are named properly, which makes it easier for them to find colors. ''' def slot_fill_combobox(self): if self.currentPalette is None: pass palette = self.currentPalette self.colorComboBox.clear() self.colorList = list() for i in range(palette.colorsCountTotal()): entry = palette.colorSetEntryByIndex(i) color = palette.colorForEntry(entry).colorForCanvas(self.canvas()) colorSquare = QPixmap(12, 12) if entry.spotColor() is True: img = colorSquare.toImage() circlePainter = QPainter() img.fill(self.colorComboBox.palette().color(QPalette.Base)) circlePainter.begin(img) brush = QBrush(Qt.SolidPattern) brush.setColor(color) circlePainter.setBrush(brush) circlePainter.pen().setWidth(0) circlePainter.drawEllipse(0, 0, 11, 11) circlePainter.end() colorSquare = QPixmap.fromImage(img) else: colorSquare.fill(color) name = entry.name() if len(entry.id()) > 0: name = entry.id() + " - " + entry.name() self.colorList.append(name) self.colorComboBox.addItem(QIcon(colorSquare), name) self.colorComboBox.setEditable(True) self.colorComboBox.setInsertPolicy(QComboBox.NoInsert) self.colorComboBox.completer().setCompletionMode( QCompleter.PopupCompletion) self.colorComboBox.completer().setCaseSensitivity(False) self.colorComboBox.completer().setFilterMode(Qt.MatchContains) def slot_get_color_from_combobox(self): if self.currentPalette is not None: entry = self.currentPalette.colorSetEntryByIndex( self.colorComboBox.currentIndex()) self.slot_swatchSelected(entry) def slot_add_entry(self): if (self.canvas()) is not None: if (self.canvas().view()) is not None: color = self.canvas().view().foregroundColor() success = self.paletteView.addEntryWithDialog(color) if success is True: self.slot_fill_combobox() def slot_add_group(self): success = self.paletteView.addGroupWithDialog() if success is True: self.slot_fill_combobox() def slot_remove_entry(self): success = self.paletteView.removeSelectedEntryWithDialog() if success is True: self.slot_fill_combobox() ''' A function for giving a gui to edit palette metadata... I also want this to be the way to edit the settings of the palette docker. ''' def slot_edit_palette_data(self): dialog = QDialog(self) tabWidget = QTabWidget() dialog.setWindowTitle(i18n("Edit Palette Data")) dialog.setLayout(QVBoxLayout()) dialog.layout().addWidget(tabWidget) paletteWidget = QWidget() paletteWidget.setLayout(QVBoxLayout()) tabWidget.addTab(paletteWidget, i18n("Palette Data")) paletteName = QLineEdit() paletteName.setText(self.cmb_palettes.currentText()) paletteWidget.layout().addWidget(paletteName) paletteColumns = QSpinBox() paletteColumns.setValue(self.currentPalette.columnCount()) paletteWidget.layout().addWidget(paletteColumns) paletteComment = QPlainTextEdit() paletteComment.appendPlainText(self.currentPalette.comment()) paletteWidget.layout().addWidget(paletteComment) buttons = QDialogButtonBox(QDialogButtonBox.Ok) dialog.layout().addWidget(buttons) buttons.accepted.connect(dialog.accept) # buttons.rejected.connect(dialog.reject()) if dialog.exec_() == QDialog.Accepted: Resource = Application.resources("palette")[ self.cmb_palettes.currentText()] Resource.setName(paletteName.text()) self.currentPalette = Palette(Resource) self.currentPalette.setColumnCount(paletteColumns.value()) self.paletteView.setPalette(self.currentPalette) self.slot_fill_combobox() self.currentPalette.setComment(paletteComment.toPlainText()) self.currentPalette.save() def slot_export_to_gimp_palette(self): palette_exporter_gimppalette.gimpPaletteExporter( self.cmb_palettes.currentText()) def slot_export_to_inkscape_svg(self): palette_exporter_inkscapeSVG.inkscapeSVGExporter( self.cmb_palettes.currentText()) def slot_sort_colors(self): colorSorter = palette_sortColors.sortColors( self.cmb_palettes.currentText()) self.paletteView.setPalette(colorSorter.palette()) def canvasChanged(self, canvas): self.cmb_palettes.clear() allPalettes = Application.resources("palette") for palette_name in allPalettes: self.cmb_palettes.addItem(palette_name) self.cmb_palettes.model().sort(0) if self.currentPalette == None and len(allPalettes.keys()) > 0: self.currentPalette = Palette(allPalettes[list( allPalettes.keys())[0]])
class FontToolBar(QToolBar): def __init__(self, pointSize, parent=None): super(FontToolBar, self).__init__(parent) auxiliaryWidth = self.fontMetrics().width('0') * 8 self.leftTextField = QLineEdit(self) self.leftTextField.setMaximumWidth(auxiliaryWidth) self.textField = QComboBox(self) self.textField.setEditable(True) completer = self.textField.completer() completer.setCaseSensitivity(Qt.CaseSensitive) self.textField.setCompleter(completer) # XXX: had to use Maximum because Preferred did entend the widget(?) self.textField.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum) items = QSettings().value("metricsWindow/comboBoxItems", comboBoxItems, str) self.textField.addItems(items) self.rightTextField = QLineEdit(self) self.rightTextField.setMaximumWidth(auxiliaryWidth) self.leftTextField.textEdited.connect(self.textField.editTextChanged) self.rightTextField.textEdited.connect(self.textField.editTextChanged) self.comboBox = QComboBox(self) self.comboBox.setEditable(True) self.comboBox.setValidator(QIntValidator(self)) for p in pointSizes: self.comboBox.addItem(str(p)) self.comboBox.setEditText(str(pointSize)) self.configBar = QPushButton(self) self.configBar.setFlat(True) self.configBar.setIcon(QIcon(":/resources/settings.svg")) self.configBar.setStyleSheet("padding: 2px 0px; padding-right: 10px") self.toolsMenu = QMenu(self) showKerning = self.toolsMenu.addAction( "Show Kerning", self.showKerning) showKerning.setCheckable(True) showMetrics = self.toolsMenu.addAction( "Show Metrics", self.showMetrics) showMetrics.setCheckable(True) self.toolsMenu.addSeparator() wrapLines = self.toolsMenu.addAction("Wrap lines", self.wrapLines) wrapLines.setCheckable(True) noWrapLines = self.toolsMenu.addAction("No wrap", self.noWrapLines) noWrapLines.setCheckable(True) self.toolsMenu.addSeparator() verticalFlip = self.toolsMenu.addAction( "Vertical flip", self.verticalFlip) verticalFlip.setCheckable(True) """ lineHeight = QWidgetAction(self.toolsMenu) lineHeight.setText("Line height:") lineHeightSlider = QSlider(Qt.Horizontal, self) # QSlider works with integers so we'll just divide by 100 what comes # out of it lineHeightSlider.setMinimum(80) lineHeightSlider.setMaximum(160) lineHeightSlider.setValue(100) #lineHeightSlider.setContentsMargins(30, 0, 30, 0) lineHeightSlider.valueChanged.connect(self.lineHeight) lineHeight.setDefaultWidget(lineHeightSlider) self.toolsMenu.addAction(lineHeight) """ wrapLinesGroup = QActionGroup(self) wrapLinesGroup.addAction(wrapLines) wrapLinesGroup.addAction(noWrapLines) wrapLines.setChecked(True) # self.toolsMenu.setActiveAction(wrapLines) self.configBar.setMenu(self.toolsMenu) self.addWidget(self.leftTextField) self.addWidget(self.textField) self.addWidget(self.rightTextField) self.addWidget(self.comboBox) self.addWidget(self.configBar) def showEvent(self, event): super(FontToolBar, self).showEvent(event) self.textField.setFocus(True) def setPointSize(self, pointSize): self.comboBox.blockSignals(True) self.comboBox.setEditText(str(pointSize)) self.comboBox.blockSignals(False) def showKerning(self): action = self.sender() self.parent().canvas.setShowKerning(action.isChecked()) def showMetrics(self): action = self.sender() self.parent().canvas.setShowMetrics(action.isChecked()) def verticalFlip(self): action = self.sender() self.parent().canvas.setVerticalFlip(action.isChecked()) def lineHeight(self, value): self.parent().canvas.setLineHeight(value / 100) def wrapLines(self): self.parent().canvas.setWrapLines(True) def noWrapLines(self): self.parent().canvas.setWrapLines(False)
class EditField(QDialog): """Dialog that allows editing of a field and it's values. When the user clicks ok, a 'donewithmyshit' (yeah yeah, I wrote this three years ago) signal is emitted containing three parameters. The first being the new field, the second that field's value and the third is the dictionary of the previous field in the form {field: value}. (Because the user might choose to edit a different tag, then the one that was chosen and you'd want to delete that one)""" donewithmyshit = pyqtSignal(str, str, object, name='donewithmyshit') def __init__(self, field=None, parent=None, field_list=None, edit=True): QDialog.__init__(self, parent) self.setWindowTitle(translate('Edit Field', 'Edit Field')) winsettings('edit_field', self) self.vbox = QVBoxLayout() label = QLabel(translate('Edit Field', "&Field")) self.tagcombo = QComboBox() self.tagcombo.setEditable(True) label.setBuddy(self.tagcombo) completer = self.tagcombo.completer() completer.setCaseSensitivity(Qt.CaseSensitive) completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion) self.tagcombo.setCompleter(completer) self.tagcombo.addItems(field_list if field_list else gettaglist()) # Get the previous field self.__oldField = field label1 = QLabel(translate('Edit Field', "&Value")) self.value = TextEdit() self.value.setTabChangesFocus(True) label1.setBuddy(self.value) okcancel = OKCancel() okcancel.okButton.setText(translate('Edit Field', 'A&dd')) if field is not None: x = self.tagcombo.findText(field[0]) if x > -1: self.tagcombo.setCurrentIndex(x) else: self.tagcombo.setEditText(field[0]) self.value.setPlainText(field[1]) if edit: okcancel.okButton.setText(translate('Edit Field', 'E&dit')) list(map(self.vbox.addWidget, [label, self.tagcombo, label1, self.value])) self.vbox.addLayout(okcancel) self.setLayout(self.vbox) okcancel.ok.connect(self.ok) okcancel.cancel.connect(self.close) self.value.setFocus() if self.__oldField else self.tagcombo.setFocus() def ok(self): self.close() self.donewithmyshit.emit( str(self.tagcombo.currentText()), str(self.value.toPlainText()), self.__oldField)
class AutonumberDialog(QDialog): newtracks = pyqtSignal(int, int, 'Qt::CheckState', int, str, str, 'Qt::CheckState', name='newtracks') def __init__(self, parent=None, minval=0, numtracks=0, enablenumtracks=False): QDialog.__init__(self, parent) self.setWindowTitle( translate('Autonumbering Wizard', "Autonumbering Wizard")) winsettings('autonumbering', self) def hbox(*widgets): box = QHBoxLayout() [box.addWidget(z) for z in widgets] box.addStretch() return box vbox = QVBoxLayout() self._start = QSpinBox() self._start.setValue(minval) self._start.setMaximum(65536) startlabel = QLabel(translate('Autonumbering Wizard', "&Start: ")) startlabel.setBuddy(self._start) vbox.addLayout(hbox(startlabel, self._start)) self._padlength = QSpinBox() self._padlength.setValue(1) self._padlength.setMaximum(65535) self._padlength.setMinimum(1) label = QLabel(translate('Autonumbering Wizard', 'Max length after padding with zeroes: ')) label.setBuddy(self._padlength) vbox.addLayout(hbox(label, self._padlength)) self._separator = QCheckBox(translate('Autonumbering Wizard', "Add track &separator ['/']: Number of tracks")) self._numtracks = QSpinBox() self._numtracks.setEnabled(False) self._numtracks.setMaximum(65535) if numtracks: self._numtracks.setValue(numtracks) self._restart_numbering = QCheckBox(translate('Autonumbering Wizard', "&Restart numbering at each directory group.")) self._restart_numbering.stateChanged.connect( self.showDirectorySplittingOptions) vbox.addLayout(hbox(self._separator, self._numtracks)) vbox.addWidget(self._restart_numbering) self.custom_numbering_widgets = [] label = QLabel(translate('Autonumbering Wizard', "Group tracks using pattern:: ")) self.grouping = QLineEdit() label.setBuddy(self.grouping) vbox.addLayout(hbox(label, self.grouping)) self.custom_numbering_widgets.extend([label, self.grouping]) label = QLabel(translate('Autonumbering Wizard', "Output field: ")) self.output_field = QComboBox() label.setBuddy(self.output_field) self.output_field.setEditable(True) completer = self.output_field.completer() completer.setCaseSensitivity(Qt.CaseSensitive) completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion) self.output_field.setCompleter(completer) self.output_field.addItems(gettaglist()) vbox.addLayout(hbox(label, self.output_field)) self.custom_numbering_widgets.extend([label, self.output_field]) self.count_by_group = QCheckBox(translate('Autonumbering Wizard', 'Increase counter only on group change')) vbox.addWidget(self.count_by_group) self.custom_numbering_widgets.append(self.count_by_group) okcancel = OKCancel() vbox.addLayout(okcancel) self.setLayout(vbox) okcancel.ok.connect(self.emitValuesAndSave) okcancel.cancel.connect(self.close) self._separator.stateChanged.connect( lambda v: self._numtracks.setEnabled(v == Qt.Checked)) # self._restart_numbering.stateChanged.connect( # self.showDirectorySplittingOptions) self._separator.setChecked(enablenumtracks) self._loadSettings() def showDirectorySplittingOptions(self, state): is_checked = state == Qt.Checked for widget in self.custom_numbering_widgets: widget.setVisible(is_checked) if is_checked: self._numtracks.setVisible(False) self._separator.setText(translate('Autonumbering Wizard', "Add track &separator ['/']")) else: self._numtracks.setVisible(True) self._separator.setText(translate('Autonumbering Wizard', "Add track &separator ['/']: Number of tracks")) def emitValuesAndSave(self): if self._numtracks.isVisible(): if self._separator.isChecked(): numtracks = self._numtracks.value() else: numtracks = -1 # Don't use totals else: if self._separator.isChecked(): numtracks = -2 # Use totals, automaticall generated else: numtracks = -1 self.close() self.newtracks.emit( self._start.value(), numtracks, self._restart_numbering.checkState(), self._padlength.value(), str(self.grouping.text()), str(self.output_field.currentText()), self.count_by_group.checkState() ) self._saveSettings() def _loadSettings(self): cparser = PuddleConfig() section = 'autonumbering' self._start.setValue(cparser.get(section, 'start', 1)) self._separator.setCheckState( cparser.get(section, 'separator', Qt.Unchecked)) self._padlength.setValue(cparser.get(section, 'padlength', 1)) self._restart_numbering.setCheckState( cparser.get(section, 'restart', Qt.Unchecked)) self.count_by_group.setCheckState( cparser.get(section, 'count_by_group', Qt.Unchecked)) self.showDirectorySplittingOptions(self._restart_numbering.checkState()) self.grouping.setText(cparser.get(section, 'grouping', '%__dirpath%')) output_field_text = cparser.get(section, 'output_field', 'track') if not output_field_text: output_field_text = 'track' last_output_field_index = self.output_field.findText(output_field_text) if last_output_field_index > -1: self.output_field.setCurrentIndex(last_output_field_index) def _saveSettings(self): cparser = PuddleConfig() section = 'autonumbering' cparser.set(section, 'start', self._start.value()) cparser.set(section, 'separator', self._separator.checkState()) cparser.set(section, 'count_by_group', self.count_by_group.checkState()) cparser.set(section, 'numtracks', self._numtracks.value()) cparser.set(section, 'restart', self._restart_numbering.checkState()) cparser.set(section, 'padlength', self._padlength.value()) cparser.set(section, 'grouping', self.grouping.text()) cparser.set(section, 'output_field', self.output_field.currentText())
class FontToolBar(QToolBar): def __init__(self, pointSize, parent=None): super(FontToolBar, self).__init__(parent) auxiliaryWidth = self.fontMetrics().width('0') * 8 self.leftTextField = QLineEdit(self) self.leftTextField.setMaximumWidth(auxiliaryWidth) self.textField = QComboBox(self) self.textField.setEditable(True) completer = self.textField.completer() completer.setCaseSensitivity(Qt.CaseSensitive) self.textField.setCompleter(completer) # XXX: had to use Maximum because Preferred did entend the widget(?) self.textField.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum) items = QSettings().value("metricsWindow/comboBoxItems", comboBoxItems, str) self.textField.addItems(items) self.rightTextField = QLineEdit(self) self.rightTextField.setMaximumWidth(auxiliaryWidth) self.leftTextField.textEdited.connect(self.textField.editTextChanged) self.rightTextField.textEdited.connect(self.textField.editTextChanged) self.comboBox = QComboBox(self) self.comboBox.setEditable(True) self.comboBox.setValidator(QIntValidator(self)) for p in pointSizes: self.comboBox.addItem(str(p)) self.comboBox.setEditText(str(pointSize)) self.configBar = QPushButton(self) self.configBar.setFlat(True) self.configBar.setIcon(QIcon(":/resources/settings.svg")) self.configBar.setStyleSheet("padding: 2px 0px; padding-right: 10px") self.toolsMenu = QMenu(self) showKerning = self.toolsMenu.addAction( self.tr("Show Kerning"), self.showKerning) showKerning.setCheckable(True) showMetrics = self.toolsMenu.addAction( self.tr("Show Metrics"), self.showMetrics) showMetrics.setCheckable(True) self.toolsMenu.addSeparator() wrapLines = self.toolsMenu.addAction(self.tr("Wrap lines"), self.wrapLines) wrapLines.setCheckable(True) wrapLines.setChecked(True) self.toolsMenu.addSeparator() verticalFlip = self.toolsMenu.addAction( self.tr("Vertical flip"), self.verticalFlip) verticalFlip.setCheckable(True) """ lineHeight = QWidgetAction(self.toolsMenu) lineHeight.setText("Line height:") lineHeightSlider = QSlider(Qt.Horizontal, self) # QSlider works with integers so we'll just divide by 100 what comes # out of it lineHeightSlider.setMinimum(80) lineHeightSlider.setMaximum(160) lineHeightSlider.setValue(100) #lineHeightSlider.setContentsMargins(30, 0, 30, 0) lineHeightSlider.valueChanged.connect(self.lineHeight) lineHeight.setDefaultWidget(lineHeightSlider) self.toolsMenu.addAction(lineHeight) """ self.configBar.setMenu(self.toolsMenu) self.addWidget(self.leftTextField) self.addWidget(self.textField) self.addWidget(self.rightTextField) self.addWidget(self.comboBox) self.addWidget(self.configBar) def showEvent(self, event): super(FontToolBar, self).showEvent(event) self.textField.setFocus(True) def setPointSize(self, pointSize): self.comboBox.blockSignals(True) self.comboBox.setEditText(str(pointSize)) self.comboBox.blockSignals(False) def showKerning(self): action = self.sender() self.parent().canvas.setShowKerning(action.isChecked()) def showMetrics(self): action = self.sender() self.parent().canvas.setShowMetrics(action.isChecked()) def verticalFlip(self): action = self.sender() self.parent().canvas.setVerticalFlip(action.isChecked()) def lineHeight(self, value): self.parent().canvas.setLineHeight(value / 100) def wrapLines(self): action = self.sender() self.parent().canvas.setWrapLines(action.isChecked())
class AddTransDialog(QDialog): def __init__(self, parent=None, title='', item=None): super(AddTransDialog, self).__init__(parent) self.setFixedWidth(300) self.setWindowTitle(title) self.setWindowIcon(Icon('money.png')) self.showMessage = self.parent().mainWindow.showMessage self.createLayout(item) def createLayout(self, item): layout = QFormLayout() types = QGroupBox("Tipo", self) self.expense = QRadioButton("Despesa") self.expense.setChecked(True) self.expense.toggled.connect(lambda: changePrefix(self)) self.income = QRadioButton("Receita") self.income.toggled.connect(lambda: changePrefix(self)) hbox = QHBoxLayout() hbox.addWidget(self.expense) hbox.addWidget(self.income) types.setLayout(hbox) layout.addRow(types) self.date = QDateEdit() self.date.setDate(QDate.currentDate()) self.date.setCalendarPopup(True) self.date.setFocusPolicy(Qt.StrongFocus) layout.addRow("Data", self.date) self.description = QLineEdit() self.description.setMaxLength(40) completer = QCompleter(DATABASE.getDescriptions()) completer.setCaseSensitivity(Qt.CaseInsensitive) completer.setCompletionMode(QCompleter.InlineCompletion) self.description.setCompleter(completer) layout.addRow("Descrição", self.description) self.category = QComboBox() self.category.setEditable(True) self.category.completer().setCompletionMode(QCompleter.PopupCompletion) categories = DATABASE.getCategories() if not categories: DATABASE.populateCategories() categories = DATABASE.getCategories() for cat in categories: self.category.addItem(cat) layout.addRow("Categoria", self.category) self.account = QComboBox() self.account.setEditable(False) accounts = DATABASE.getAccounts() for acc in accounts: self.account.addItem(acc) layout.addRow("Conta", self.account) self.value = QDoubleSpinBox() self.value.setDecimals(2) self.value.setSingleStep(100) self.value.setRange(0, 1000000000) layout.addRow("Valor", self.value) divBox = QHBoxLayout() self.initial = QSpinBox() self.initial.setRange(1, 1000) label = QLabel(" de ") label.setAlignment(Qt.AlignCenter) self.subdivision = QSpinBox() self.subdivision.setRange(1, 1000) self.subdivision.setSuffix(" parcelas") self.subdivision.setAlignment(Qt.AlignCenter) divBox.addWidget(self.initial) divBox.addWidget(label) divBox.addWidget(self.subdivision) layout.addRow("Parcelas", divBox) sublayout = QHBoxLayout() self.ok = QPushButton("Adicionar") self.ok.clicked.connect(self.accept) if not accounts: self.ok.setEnabled(False) cancel = QPushButton("Cancelar") cancel.clicked.connect(self.reject) sublayout.addWidget(self.ok) sublayout.addWidget(cancel) layout.addRow(sublayout) if item: info = DATABASE.getTransactions(ident=item.ident) if info[-1] >= 0: self.income.setChecked(True) self.value.setPrefix("R$ ") else: self.expense.setChecked(True) self.value.setPrefix("R$ -") self.date.setDate(QDate(info[3], info[2], info[1])) self.description.setText(info[4]) idx = self.category.findText(info[5], Qt.MatchExactly) self.category.setCurrentIndex(idx) idx = self.account.findText(info[7], Qt.MatchExactly) self.account.setCurrentIndex(idx) self.value.setValue(abs(info[8])) self.ok.setText("Editar") self.initial.setEnabled(False) label.setEnabled(False) self.subdivision.setEnabled(False) self.setLayout(layout) def process(self, item): if DATABASE.getCategories(self.category.currentText()): self.insertTransaction(item) self.parent().mainWindow.loadInfo() else: message = QMessageBox( QMessageBox.Warning, "Categoria Inexistente", "Deseja adicionar a categoria %s" % self.category.currentText(), QMessageBox.Ok | QMessageBox.Cancel) resultMsg = message.exec_() if resultMsg == QMessageBox.Ok: self.insertTransaction(item, True) self.parent().mainWindow.loadInfo() def insertTransaction(self, item, newCategory=False): if self.expense.isChecked(): value = -self.value.value() else: value = self.value.value() if not item: value = value / self.subdivision.value() count = 0 for i in range(self.initial.value(), self.subdivision.value() + 1): date = self.date.date().addMonths(count) transaction = [date.day(), date.month(), date.year()] if self.subdivision.value() > 1: transaction += [ self.description.text() + " (%d/%d)" % (i, self.subdivision.value()) ] else: transaction += [self.description.text()] if newCategory: transaction += [self.category.currentText(), None] else: transaction += [ self.category.currentText(), DATABASE.getCategories(self.category.currentText(), infos=True)[1] ] transaction += [self.account.currentText(), value] DATABASE.addTransaction(transaction) self.showMessage("Transação Adicionada.") count += 1 else: date = self.date.date() transaction = [date.day(), date.month(), date.year()] transaction += [self.description.text()] if newCategory: transaction += [self.category.currentText(), None] else: transaction += [ self.category.currentText(), DATABASE.getCategories(self.category.currentText(), infos=True)[1] ] transaction += [self.account.currentText(), value, item.ident] DATABASE.updateTransaction(transaction) self.showMessage("Transação Editada.")
print(combobox.currentText()) app = QApplication(sys.argv) combobox = QComboBox() #"Select one...", ITEMS = [ "", "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ] combobox.addItems(ITEMS) combobox.setEditable(True) combobox.completer().setCompletionMode(QCompleter.PopupCompletion) #combobox.setCurrentIndex(1) #combobox.setCurrentText("Python") combobox.currentIndexChanged.connect(printText) combobox.show() # The mainloop of the application. The event handling starts from this point. # The exec_() method has an underscore. It is because the exec is a Python keyword. And thus, exec_() was used instead. exit_code = app.exec_() # The sys.exit() method ensures a clean exit. # The environment will be informed, how the application ended. sys.exit(exit_code)
class ApplicationWindow(QtWidgets.QMainWindow): def __init__(self): QtWidgets.QMainWindow.__init__(self) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.title = 'Polynomial Regression' self.left = 50 self.top = 100 self.width = 1200 self.height = 120 self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.setFixedSize(self.size()) self.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.CustomizeWindowHint | QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowStaysOnTopHint) self.featureX = QComboBox(self) self.featureX.setToolTip('Select feature for X axis') self.featureX.move(15, 14) self.featureX.resize(840, 20) label = QLabel('X-Axis Feature', self) label.move(19, 16) label.resize(100, 50) self.featureY = QComboBox(self) self.featureY.setToolTip('Select feature for Y axis') self.featureY.move(15, 60) self.featureY.resize(840, 20) label = QLabel('Y-Axis Feature', self) label.move(19, 62) label.resize(100, 50) # descriptions = getDescriptions() # descriptions = [d.lower() for d in descriptions] # descriptions.sort() self.featureX.setInsertPolicy(QComboBox.NoInsert) self.featureX.setEditable(True) self.featureX.setCompleter(QCompleter()) self.featureX.completer().setCompletionMode( QCompleter.UnfilteredPopupCompletion) self.featureY.setInsertPolicy(QComboBox.NoInsert) self.featureY.setEditable(True) self.featureY.setCompleter(QCompleter()) self.featureY.completer().setCompletionMode( QCompleter.UnfilteredPopupCompletion) self.order = QComboBox(self) self.order.setToolTip('Select order of polynomial fit') self.order.move(915, 14) self.order.resize(50, 23) label = QLabel(' Order of\nPolynomial', self) label.move(906, 17) label.resize(120, 75) for i in range(1, 10): self.order.addItem(str(i)) # descriptions = getDescriptions() # descriptions.sort() # for d in descriptions: # if (d != "bottom depth" # and d != "top depth" # and d != "Cost per unit" # and d != "Name of mud engineer"): continue # self.featureY.addItem(d) # self.featureX.addItem(d) plotButton = QPushButton('Plot', self) plotButton.setToolTip('Use button to plot poly regression') # plotButton.clicked.connect(self.parent().plotPolyRegression) plotButton.move(1020, 18) plotButton.resize(90, 90)
class EjournalApp(QWidget): """ This app facilitates the markup of journal articles. There are two options: Generate the markdown file and Push to Jekyll. The first takes user input and formats a markdown file for the user to then add additional markup to. The second takes a directory and pushes that directory to Jekyll for HTML generation. """ ''' =========Variables for journals========== Title of Journal: journal_title Title of Article: art_title Journal Volume: j_vol Journal Issue: j_issue Season: j_ssn Year: j_year Filename: j_filename Dictionary of Authors: author_dict Article Content: content Article References: references ''' def __init__(self): """ General layout is established and the create_ui method is invoked to initialize the app's UI """ super().__init__() self.container = QVBoxLayout(self) self.form_widget = QWidget(self) self.form_layout = QFormLayout() self.layout = QVBoxLayout(self.form_widget) self.init_gui = 0 self.setWindowTitle("Ejournal Editor") self.create_ui() def clear_layout_except(self, opt_removal=""): """ Clears the UI of every object except for the object passed in as a param. If no object is passed in, it clears everything. """ # clear the widgets that may be on the form_layout and btn_container if opt_removal == '': for i in reversed(range(self.form_layout.count())): self.form_layout.itemAt(i).widget().deleteLater() for i in reversed(range(self.btn_container.count())): if self.btn_container.itemAt(i).widget() is None: continue else: self.btn_container.itemAt(i).widget().deleteLater() else: for i in reversed(range(self.form_layout.count())): if self.form_layout.itemAt(i).widget().whatsThis() == \ opt_removal: continue else: self.form_layout.itemAt(i).widget().deleteLater() def generate_md(self): """ This method is invoked after the user has entered the references. It creates a MDGenerator Class object and invokes its generate_md_file method, which creates the Markdown file. """ self.references = self.ref_tb.toPlainText() j_file_generator = MdGenerator(self.journal_title, self.art_title, self.j_vol, self.j_issue, self.j_ssn, self.j_year, self.j_filename, self.author_dict, self.content, self.references) j_file_generator.generate_md_file() notice = QMessageBox.information(self, 'Notice', "{}.md was created".format(self.j_filename.lower()), QMessageBox.Ok) def add_ref(self): """ This method generates a text area in which the user will input the article's references """ # Sets the content to a global variable self.content = self.content_tb.toPlainText() self.clear_layout_except("back_btn") # instructions for the user on signifiers for the MDGenerator class ref_lb = QLabel("""Copy and paste references below.\n\n Formatting Key:\n\n Reference:\t\tr[*]] """) self.ref_tb = QTextEdit() self.ref_tb.setAcceptRichText(True) self.ref_tb.setMinimumSize(400, 400) submit_btn = QPushButton("Submit and Generate MD File") submit_btn.clicked.connect(self.generate_md) self.form_layout.addRow(ref_lb) self.form_layout.addRow(self.ref_tb) self.form_layout.addRow(submit_btn) def add_content(self): """ This method generates a text area in which the user will input the article content """ self.clear_layout_except("back_btn") # instructions for the user on signifiers for the MDGenerator class content_lb = QLabel() if self.j_filename == "clip": content_lb.setText("""Copy and paste content below.\n\n Formatting Key:\n\n Book title:\t\t=\n By-line:\t\t==\n Genres:\t\t-=\n Publisher:\t\t===\n ISBN:\t\t-==\n Entire body:\t>>*<<\n\n If the body contains multiple paragraphs, each paragraph after the first gets this put before it:\n \t\tp[\n\n * Represents the content\n\n Signature:\n Name:\t\t;=\n Location:\t\t;== """) else: content_lb.setText("""Copy and paste content below.\n\n Formatting Key:\n\n Paragraph:\t\tp[\n Paragraph with bigFirst:\tpb[\n Section header:\t\th[*]\n Blockquote:\t\tq[*]\n\n * Represents the content """) self.content_tb = QTextEdit() self.content_tb.setAcceptRichText(True) self.content_tb.setMinimumSize(400, 400) submit_btn = QPushButton("Submit") submit_btn.clicked.connect(self.add_ref) self.form_layout.addRow(content_lb) self.form_layout.addRow(self.content_tb) self.form_layout.addRow(submit_btn) def author_validation(self): """ Validation check for author input. Displays an appropriate error to the error_lb if not valid. """ valid = False for i in range(int(self.author_cb.currentText())): if eval('self.firstname_le{}.text().strip() == ""'.format(i)) \ or \ eval('self.lastname_le{}.text().strip() == ""'.format(i)): self.error_lb.setText("First and last names cannot be blank") break elif self.journal_title == \ "JCTE" and eval('self.affil_le{}.text().strip() == ""'.format(i)): self.error_lb.setText("Affiliation cannot be blank") break else: if i == int(self.author_cb.currentText()) - 1: valid = True # when the form passes validation, the author's names and their # affiliation, if JCTE, are added to dictionaries if valid: self.author_dict = dict() if "Clip" in self.art_title: # currently, ALAN's Clip&File # has an author, but the filename is clip self.j_filename = "clip" else: self.j_filename = self.lastname_le0.text().strip() for i in range(int(self.author_cb.currentText())): auth_name = eval('" ".join((self.prefix_le{}.text(), \ self.firstname_le{}.text(),'.format(i, i) + 'self.middle_le{}.text())).strip()'.format(i)) auth_name = eval('" ".join((auth_name, \ self.suffix_cb{}.currentText())).strip()'.format(i)) auth_name = eval('", ".join((self.lastname_le{}.text(),\ auth_name))'.format(i)) if self.journal_title == "JCTE": self.author_dict[i] = \ (eval('self.affil_le{}.text().strip()'.format(i)),\ auth_name) else: self.author_dict[i] = auth_name self.add_content() def update_authors(self): """ This method does the heavy-lifting for the author building. It's called every time the value in the author_cb changes. """ # sets tuple to hold acceptable suffixes self.suffixes = (" ", "CPA", "D.C.", "D.D.", "D.D.S.", "D.M.D.", "D.O.", "D.V.M.", "Ed.D.", "Esq.", "II", "III", "IV", "J.D.", "Jr.", "LL.D.", "M.D.", "O.D.", "Ph.D.", "R.N.", "R.N.C.", "Sr.") self.clear_layout_except("author_cb") # iterates through based on the value of author_cb, # creating i number of author input sections for i in range(int(self.author_cb.currentText())): self.prefix_lb = QLabel("Prefix: ") # exec and eval functions are called to insert string # formatting into variables b/c of iteration exec('self.prefix_le{} = QLineEdit()'.format(i)) exec('self.prefix_le{}.setMinimumSize(300, 10)'.format(i)) self.firstname_lb = QLabel("First name: ") exec('self.firstname_le{} = QLineEdit()'.format(i)) exec('self.firstname_le{}.setMinimumSize(300, 10)'.format(i)) self.middle_lb = QLabel("Middle name: ") exec('self.middle_le{} = QLineEdit()'.format(i)) exec('self.middle_le{}.setMinimumSize(300, 10)'.format(i)) self.lastname_lb = QLabel("Last name: ") exec('self.lastname_le{} = QLineEdit()'.format(i)) exec('self.lastname_le{}.setMinimumSize(300, 10)'.format(i)) self.suffix_lb = QLabel("Suffix: ") exec('self.suffix_cb{} = QComboBox()'.format(i)) exec('self.suffix_cb{}.setMinimumSize(300, 10)'.format(i)) for suffix in self.suffixes: eval('self.suffix_cb{}'.format(i)).addItem(suffix) self.spacer_lb = QLabel("--------------------------") # Creates Afiliations section if the journal is JCTE if self.journal_title == "JCTE": self.affil_lb = QLabel("Affiliations:") exec('self.affil_le{} = QLineEdit()'.format(i)) exec('self.affil_le{}.setMinimumSize(300, 10)'.format(i)) self.spacer_lb.setMinimumSize(300, 10) exec('self.form_layout.addRow(self.prefix_lb,\ self.prefix_le{})'.format(i)) exec('self.form_layout.addRow(self.firstname_lb,\ self.firstname_le{})'.format(i)) exec('self.form_layout.addRow(self.middle_lb,\ self.middle_le{})'.format(i)) exec('self.form_layout.addRow(self.lastname_lb,\ self.lastname_le{})'.format(i)) exec('self.form_layout.addRow(self.suffix_lb,\ self.suffix_cb{})'.format(i)) self.form_layout.addRow(self.spacer_lb) # JCTE has special affiliations field for its authors if self.journal_title == "JCTE": exec('self.form_layout.addRow(self.affil_lb,\ self.affil_le{})'.format(i)) self.form_layout.addRow(self.spacer_lb) content_btn = QPushButton("Add content") content_btn.clicked.connect(self.author_validation) self.error_lb = QLabel("") self.error_lb.setMinimumSize(300, 10) self.form_layout.addRow(self.error_lb) self.form_layout.addRow(content_btn) def add_authors(self): """ Method that builds the screen and dropdown combobox for the authors """ self.clear_layout_except("back_btn") self.author_cb = QComboBox() for i in range(1, 11): i = str(i) self.author_cb.addItem(i) self.author_cb.setWhatsThis("author_cb") self.form_layout.addRow(self.author_cb) # initial call to update_authors sets the screen up for one author self.update_authors() # this line watches for the value to change in the dropdown combobox # if it does change, update_authors is called again to # build screen based on new number of authors self.author_cb.activated[str].connect(self.update_authors) def metadata_validate(self, has_authors=True): """ Method to validate article metadata """ valid = False # Place variables in tuple for validation data = ( self.title_le.text().strip(), self.vol_cb.currentText(), self.issue_cb.currentText(), self.ssn_cb.currentText(), self.year_cb.currentText() ) for d in data: if d == "": # Checks for blanks self.error_lb.setText("No field can be left blank.") break # Each of the following checks for inputs that are not an option elif data.index(d) == 1 and self.vol_cb.findText(d) == -1: self.error_lb.setText("Please select a volume from the list.") break elif data.index(d) == 2 and self.issue_cb.findText(d) == -1: self.error_lb.setText("Please select an issue from the list.") break elif data.index(d) == 3 and self.ssn_cb.findText(d) == -1: self.error_lb.setText("Please select a season from the list.") break elif data.index(d) == 4 and self.year_cb.findText(d) == -1: self.error_lb.setText("Please select a year from the list.") break else: if data.index(d) == 4: # if all checks pass and it's the last # item in the list, validate the data valid = True if valid: # if the data are valid self.art_title = data[0] self.j_vol = data[1] self.j_issue = data[2] self.j_ssn = data[3] self.j_year = data[4] if has_authors: self.add_authors() else: self.author_dict = dict() # set the author var to empty if "Clip" in self.art_title: self.j_filename = "clip" elif "Editor" in self.art_title: self.j_filename = "editors" elif "Manuscript" in self.art_title: self.j_filename = "manuscript" elif "Misc" in self.art_title: self.j_filename = "miscellany" elif "Instruction" in self.art_title: self.j_filename = "authors" elif "Guideline" in self.art_title: self.j_filename = "guidelines" elif "Stories" in self.art_title: self.j_filename = "stories" self.add_content() def show_journal_metadata(self, journal_title): """ Second screen user is presented. It takes the title of the Journal as a param to set it globally after the corresponding btn was chosen on the previous screen--in the show_journal_chooser method. """ self.clear_layout_except("back_btn") self.journal_title = journal_title issue_range = ("1", "2", "3", "4") seasons = ("Fall", "Winter", "Spring", "Summer") header_lb = QLabel(self.journal_title + " Issue Metadata") title_lb = QLabel("Title: ") self.title_le = QLineEdit() self.title_le.setMinimumSize(300, 10) vol_lb = QLabel("Volume: ") self.vol_cb = QComboBox() self.vol_cb.setEditable(True) # set autocompleters self.vol_cb.completer().setCompletionMode(QCompleter.PopupCompletion) self.vol_cb.setMinimumSize(300, 10) for i in range(1, 201): i = str(i) self.vol_cb.addItem(i) issue_lb = QLabel("Issue: ") self.issue_cb = QComboBox() self.issue_cb.setEditable(True) self.issue_cb.completer().setCompletionMode(QCompleter.PopupCompletion) self.issue_cb.setMinimumSize(300, 10) for i in issue_range: self.issue_cb.addItem(i) ssn_lb = QLabel("Season: ") self.ssn_cb = QComboBox() self.ssn_cb.setEditable(True) self.ssn_cb.completer().setCompletionMode(QCompleter.PopupCompletion) self.ssn_cb.setMinimumSize(300, 10) for ssn in seasons: self.ssn_cb.addItem(ssn) year_lb = QLabel("Year: ") self.year_cb = QComboBox() self.year_cb.setEditable(True) self.year_cb.completer().setCompletionMode(QCompleter.PopupCompletion) self.year_cb.setMinimumSize(300, 10) for i in range(1900, 2101): i = str(i) self.year_cb.addItem(i) authors_btn = QPushButton("Add Authors", self) no_authors_btn = QPushButton("No Authors", self) self.error_lb = QLabel("") # error label authors_btn.clicked.connect(partial(self.metadata_validate, True)) no_authors_btn.clicked.connect(partial(self.metadata_validate, False)) self.form_layout.addRow(header_lb) self.form_layout.addRow(title_lb, self.title_le) self.form_layout.addRow(vol_lb, self.vol_cb) self.form_layout.addRow(issue_lb, self.issue_cb) self.form_layout.addRow(ssn_lb, self.ssn_cb) self.form_layout.addRow(year_lb, self.year_cb) self.form_layout.addRow(authors_btn) self.form_layout.addRow(no_authors_btn) self.form_layout.addRow(self.error_lb) def show_journal_chooser(self): """ First metadata option for user when generation MD file """ self.clear_layout_except("back_btn") self.journalList = ('ALAN', 'JCTE', 'JOTS', 'JTE', 'VALib') for journal in self.journalList: btn = QPushButton(journal, self) btn.setMinimumSize(300, 40) btn.setMaximumSize(300, 40) btn.setWhatsThis(journal) btn.clicked.connect(partial(self.show_journal_metadata, journal)) self.form_layout.addRow(btn) self.btn_container = QHBoxLayout() self.btn_container.addStretch(1) self.back_btn = QPushButton("Back to options", self) self.back_btn.setWhatsThis("back_btn") self.back_btn.setMinimumSize(150, 40) self.back_btn.setMaximumSize(150, 40) self.back_btn.clicked.connect(self.create_ui) self.btn_container.addWidget(self.back_btn) # Back button is added to the container # it remains unless a complete reset of the UI is called self.layout.addLayout(self.btn_container) def show_directory_chooser(self): """ Opens a directory browser for the user to choose the dir containing the MD files. Once a directory is chosen, it is passed on to a Jekyll Class Object, which generates the HTMl via the Ruby Jekyll Generator (not to be confused with the Jekyll Class Object created by this program). """ user = os.getlogin() md_directory = QFileDialog.getExistingDirectory(None, 'Select folder:', '/Users/' + user + '/Desktop', QFileDialog.ShowDirsOnly) # Creates a Jekyll object and generates the HTML files if md_directory: jekyll = Jekyll(md_directory) jekyll.serve_html_files() notice = QMessageBox.information(self, 'Notice', "HTML files were generated", QMessageBox.Ok) del jekyll def create_ui(self): """ Sets up the main UI screen for the App. """ # If first time, added everything to the layout if self.init_gui == 0: self.md_btn = QPushButton('Generate the Markdown file', self) self.jekyll_btn = QPushButton('Push to Jekyll', self) self.md_btn.setMinimumSize(300, 40) self.md_btn.setMaximumSize(300, 40) self.jekyll_btn.setMinimumSize(300, 40) self.jekyll_btn.setMaximumSize(300, 40) self.md_btn.clicked.connect(self.show_journal_chooser) self.jekyll_btn.clicked.connect(self.show_directory_chooser) self.form_layout.addRow(self.md_btn) self.form_layout.addRow(self.jekyll_btn) self.setMinimumSize(800, 700) self.scroll_area = QScrollArea() self.scroll_area.setWidgetResizable(True) self.container.addWidget(self.scroll_area) self.layout.addLayout(self.form_layout) self.scroll_area.setWidget(self.form_widget) self.init_gui = 1 # i.e., Back to Options button has been pressed, re-init the UI else: self.clear_layout_except() self.md_btn = QPushButton('Generate the Markdown file', self) self.jekyll_btn = QPushButton('Push to Jekyll', self) self.md_btn.setMinimumSize(300, 40) self.md_btn.setMaximumSize(300, 40) self.jekyll_btn.setMinimumSize(300, 40) self.jekyll_btn.setMaximumSize(300, 40) self.md_btn.clicked.connect(self.show_journal_chooser) self.jekyll_btn.clicked.connect(self.show_directory_chooser) self.form_layout.addRow(self.md_btn) self.form_layout.addRow(self.jekyll_btn) self.setMinimumSize(800, 700) self.show()