def choice(self, title, msg, choices): vbox = QVBoxLayout() self.set_layout(vbox) vbox.addWidget(QLabel(title)) gb2 = QGroupBox(msg) vbox.addWidget(gb2) vbox2 = QVBoxLayout() gb2.setLayout(vbox2) group2 = QButtonGroup() for i, c in enumerate(choices): button = QRadioButton(gb2) button.setText(c[1]) vbox2.addWidget(button) group2.addButton(button) group2.setId(button, i) if i == 0: button.setChecked(True) vbox.addStretch(1) vbox.addLayout(Buttons(CancelButton(self), OkButton(self, _('Next')))) if not self.exec_(): return wallet_type = choices[group2.checkedId()][0] return wallet_type
def initUI(self): # local variable that records which radio button is clicked self.choice = 1 # welcome message welcomeMsg = QLabel(self) welcomeMsg.setText("Welcome to the PyQt Interface!") welcomeMsg.setAlignment(Qt.AlignCenter) menu = QLabel(self) menu.setText("Menu") # create buttons & connect them with function btnClicked btn1 = QRadioButton(self) btn1.setText("1. Create montages recursively from given directory and sub-directories") btn1.setChecked(True) btn1.toggled.connect(lambda:self.btnClicked(1)) btn2 = QRadioButton(self) btn2.setText("2. Create montages from provided CSV files (split by categories or bins)") btn2.toggled.connect(lambda:self.btnClicked(2)) btn3 = QRadioButton(self) btn3.setText("3. Create vertical montage from provided CSV file") btn3.toggled.connect(lambda:self.btnClicked(3)) btn4 = QRadioButton(self) btn4.setText("4. Create image histogram from provided CSV file") btn4.toggled.connect(lambda:self.btnClicked(4)) btn5 = QRadioButton(self) btn5.setText("5. Create scatter plot from provided CSV file") btn5.toggled.connect(lambda:self.btnClicked(5)) quit = QPushButton(self) quit.setText("Quit") enter = QPushButton(self) enter.setText("Enter") instr = QPushButton(self) instr.setText("Instruction") self.setStyleSheet('QLabel {font-family: cursive, sans-serif; font-weight: 500; font-size: 16px; color: #A0522D;} QRadioButton {font-family: cursive, sans-serif; font-weight: 300; font-size: 16px; color: #8B4513;} QPushButton {font-family: cursive, sans-serif; font-weight: 500; font-size: 16px; color: #CD853F; }') welcomeMsg.setStyleSheet('QLabel {font-weight: 900;font-size: 20px;}') # set layout mbox = QGridLayout(self) mbox.addWidget(welcomeMsg, 1, 1) mbox.addWidget(menu,2,1) mbox.addWidget(btn1,3,1) mbox.addWidget(btn2,4,1) mbox.addWidget(btn3,5,1) mbox.addWidget(btn4,6,1) mbox.addWidget(btn5,7,1) mbox.addWidget(quit,8,0) mbox.addWidget(enter,8,2) mbox.addWidget(instr,8,1) self.setLayout(mbox) # connect the click event with a function enter.clicked.connect(self.nextPage) quit.clicked.connect(self.close) instr.clicked.connect(self.instruction) # set background as transparent palette = QPalette() palette.setBrush(QPalette.Background,QBrush(QPixmap())) self.setPalette(palette)
def makeSortButton(name, sortFunction): bname = "%sSortButton" % name button = QRadioButton(self.sortBox) setattr(self, bname, button) def buttonClicked(): self.__sortOrder = name self.model.setSortOrder(sortFunction) self.connect(button, SIGNAL("clicked()"), buttonClicked) self.sortLayout.addWidget(button) button.setText("By %s" % name.capitalize())
def makeOddsButton(name, oddsDisplayer): bname = "%sButton" % name button = QRadioButton(self.oddsGroupBox) setattr(self, bname, button) def buttonClicked(): self.__oddsDisplay = name self.model.setOddsDisplay(oddsDisplayer) self.connect(button, SIGNAL("clicked()"), buttonClicked) button.setEnabled(oddsDisplayer.implemented) self.oddsLayout.addWidget(button) button.setText(name.capitalize())
def network_dialog(self): # skip this if config already exists if self.config.get('server') is not None: return grid = QGridLayout() grid.setSpacing(5) label = QLabel(_( "Electrum communicates with remote servers to get ", 'information about your transactions and addresses. ', 'The servers all fulfil the same purpose only ', 'differing in hardware. In most cases you simply ', 'want to let Electrum pick one at random if you ', 'have a preference though feel free to select a server manually.') + "\n\n" + _( "How do you want to connect to a server:") + " ") label.setWordWrap(True) grid.addWidget(label, 0, 0) gb = QGroupBox() b1 = QRadioButton(gb) b1.setText(_("Auto connect")) b1.setChecked(True) b2 = QRadioButton(gb) b2.setText(_("Select server manually")) # b3 = QRadioButton(gb) # b3.setText(_("Stay offline")) grid.addWidget(b1, 1, 0) grid.addWidget(b2, 2, 0) # grid.addWidget(b3, 3, 0) vbox = QVBoxLayout() vbox.addLayout(grid) vbox.addStretch(1) vbox.addLayout(Buttons(CancelButton(self), OkButton(self, _('Next')))) self.set_layout(vbox) if not self.exec_(): return if b2.isChecked(): return NetworkDialog(self.network, self.config, None).do_exec() else: self.config.set_key('auto_connect', True, True) return
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 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 Book(_base.Group): @staticmethod def title(_=_base.translate): return _("Book") def accepts(self): return (BookPart, Score, StaffGroup, _base.Part) def createWidgets(self, layout): self.bookOutputInfo = QLabel(wordWrap=True) self.bookOutputLabel = QLabel() self.bookOutput = widgets.lineedit.LineEdit() self.bookOutputFileName = QRadioButton() self.bookOutputSuffix = QRadioButton(checked=True) layout.addWidget(self.bookOutputInfo) grid = QGridLayout(spacing=0) grid.addWidget(self.bookOutputLabel, 0, 0) grid.addWidget(self.bookOutput, 0, 1, 1, 2) grid.addWidget(self.bookOutputFileName, 1, 1) grid.addWidget(self.bookOutputSuffix, 1, 2) layout.addLayout(grid) def translateWidgets(self): self.bookOutputInfo.setText( _("<p>Here you can specify a filename or suffix (without extension) " "to set the names of generated output files for this book.</p>\n" "<p>If you choose \"Suffix\" the entered name will be appended " "to the document's file name; if you choose \"Filename\", just " "the entered name will be used.</p>")) self.bookOutputLabel.setText(_("Output Filename:")) self.bookOutputFileName.setText(_("Filename")) self.bookOutputSuffix.setText(_("Suffix")) def makeNode(self, node): book = ly.dom.Book(node) name = self.bookOutput.text().strip() if name: cmd = 'bookOutputName' if self.bookOutputFileName.isChecked( ) else 'bookOutputSuffix' ly.dom.Line(r'\{0} "{1}"'.format(cmd, name.replace('"', r'\"')), book) return book
class Book(_base.Group): @staticmethod def title(_=_base.translate): return _("Book") def accepts(self): return (BookPart, Score, StaffGroup, _base.Part) def createWidgets(self, layout): self.bookOutputInfo = QLabel(wordWrap=True) self.bookOutputLabel = QLabel() self.bookOutput = widgets.lineedit.LineEdit() self.bookOutputFileName = QRadioButton() self.bookOutputSuffix = QRadioButton(checked=True) layout.addWidget(self.bookOutputInfo) grid = QGridLayout(spacing=0) grid.addWidget(self.bookOutputLabel, 0, 0) grid.addWidget(self.bookOutput, 0, 1, 1, 2) grid.addWidget(self.bookOutputFileName, 1, 1) grid.addWidget(self.bookOutputSuffix, 1, 2) layout.addLayout(grid) def translateWidgets(self): self.bookOutputInfo.setText(_( "<p>Here you can specify a filename or suffix (without extension) " "to set the names of generated output files for this book.</p>\n" "<p>If you choose \"Suffix\" the entered name will be appended " "to the document's file name; if you choose \"Filename\", just " "the entered name will be used.</p>")) self.bookOutputLabel.setText(_("Output Filename:")) self.bookOutputFileName.setText(_("Filename")) self.bookOutputSuffix.setText(_("Suffix")) def makeNode(self, node): book = ly.dom.Book(node) name = self.bookOutput.text().strip() if name: cmd = 'bookOutputName' if self.bookOutputFileName.isChecked() else 'bookOutputSuffix' ly.dom.Line(r'\{0} "{1}"'.format(cmd, name.replace('"', r'\"')), book) return book
def _update_buttons(self): if self._spacer is not None: self._layout.removeItem(self._spacer) to_remove = self._buttons[len(self._labels):] for button in to_remove: self._layout.removeWidget(button) button.setParent(None) del self._buttons[len(self._labels):] to_add = self._labels[len(self._buttons):] for _ in to_add: button = QRadioButton(self) self._buttons.append(button) self._layout.addWidget(button) button.toggled.connect(self.buttonToggled) if self._spacer is not None: self._layout.addItem(self._spacer) if not self._buttons: return for button, label in zip(self._buttons, self._labels): button.setText(label) self._update_selection()
class StartSession(preferences.Group): def __init__(self, page): super(StartSession, self).__init__(page) grid = QGridLayout() self.setLayout(grid) def changed(): self.changed.emit() self.combo.setEnabled(self.custom.isChecked()) self.none = QRadioButton(toggled=changed) self.lastused = QRadioButton(toggled=changed) self.custom = QRadioButton(toggled=changed) self.combo = QComboBox(currentIndexChanged=changed) grid.addWidget(self.none, 0, 0, 1, 2) grid.addWidget(self.lastused, 1, 0, 1, 2) grid.addWidget(self.custom, 2, 0, 1, 1) grid.addWidget(self.combo, 2, 1, 1, 1) app.translateUI(self) def translateUI(self): self.setTitle( _("Session to load if Frescobaldi is started without arguments")) self.none.setText(_("Start with no session")) self.lastused.setText(_("Start with last used session")) self.custom.setText(_("Start with session:")) def loadSettings(self): s = QSettings() s.beginGroup("session") startup = s.value("startup", "none", type("")) if startup == "lastused": self.lastused.setChecked(True) elif startup == "custom": self.custom.setChecked(True) else: self.none.setChecked(True) sessionNames = sessions.sessionNames() self.combo.clear() self.combo.addItems(sessionNames) custom = s.value("custom", "", type("")) if custom in sessionNames: self.combo.setCurrentIndex(sessionNames.index(custom)) def saveSettings(self): s = QSettings() s.beginGroup("session") s.setValue("custom", self.combo.currentText()) if self.custom.isChecked(): startup = "custom" elif self.lastused.isChecked(): startup = "lastused" else: startup = "none" s.setValue("startup", startup)
class StartSession(preferences.Group): def __init__(self, page): super(StartSession, self).__init__(page) grid = QGridLayout() self.setLayout(grid) def changed(): self.changed.emit() self.combo.setEnabled(self.custom.isChecked()) self.none = QRadioButton(toggled=changed) self.lastused = QRadioButton(toggled=changed) self.custom = QRadioButton(toggled=changed) self.combo = QComboBox(currentIndexChanged=changed) grid.addWidget(self.none, 0, 0, 1, 2) grid.addWidget(self.lastused, 1, 0, 1, 2) grid.addWidget(self.custom, 2, 0, 1, 1) grid.addWidget(self.combo, 2, 1, 1, 1) app.translateUI(self) def translateUI(self): self.setTitle(_("Session to load if Frescobaldi is started without arguments")) self.none.setText(_("Start with no session")) self.lastused.setText(_("Start with last used session")) self.custom.setText(_("Start with session:")) def loadSettings(self): s = QSettings() s.beginGroup("session") startup = s.value("startup", "none", type("")) if startup == "lastused": self.lastused.setChecked(True) elif startup == "custom": self.custom.setChecked(True) else: self.none.setChecked(True) sessionNames = sessions.sessionNames() self.combo.clear() self.combo.addItems(sessionNames) custom = s.value("custom", "", type("")) if custom in sessionNames: self.combo.setCurrentIndex(sessionNames.index(custom)) def saveSettings(self): s = QSettings() s.beginGroup("session") s.setValue("custom", self.combo.currentText()) if self.custom.isChecked(): startup = "custom" elif self.lastused.isChecked(): startup = "lastused" else: startup = "none" s.setValue("startup", startup)
class ShortcutEditDialog(QDialog): """A modal dialog to view and/or edit keyboard shortcuts.""" def __init__(self, parent=None): super(ShortcutEditDialog, self).__init__(parent) self.setMinimumWidth(400) # create gui layout = QVBoxLayout() layout.setSpacing(10) self.setLayout(layout) top = QHBoxLayout() top.setSpacing(4) p = self.toppixmap = QLabel() l = self.toplabel = QLabel() l.setWordWrap(True) top.addWidget(p) top.addWidget(l, 1) layout.addLayout(top) grid = QGridLayout() grid.setSpacing(4) grid.setColumnStretch(1, 2) layout.addLayout(grid) self.buttonDefault = QRadioButton(self) self.buttonNone = QRadioButton(self) self.buttonCustom = QRadioButton(self) grid.addWidget(self.buttonDefault, 0, 0, 1, 2) grid.addWidget(self.buttonNone, 1, 0, 1, 2) grid.addWidget(self.buttonCustom, 2, 0, 1, 2) self.keybuttons = [] self.keylabels = [] for num in range(4): l = QLabel(self) l.setStyleSheet("margin-left: 2em;") l.setAlignment(Qt.AlignRight | Qt.AlignVCenter) b = KeySequenceWidget(self) b.keySequenceChanged.connect(self.slotKeySequenceChanged) l.setBuddy(b) self.keylabels.append(l) self.keybuttons.append(b) grid.addWidget(l, num+3, 0) grid.addWidget(b, num+3, 1) layout.addWidget(Separator(self)) b = QDialogButtonBox(self) b.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) layout.addWidget(b) b.accepted.connect(self.accept) b.rejected.connect(self.reject) app.translateUI(self) def translateUI(self): self.setWindowTitle(app.caption(_("window title", "Edit Shortcut"))) self.buttonNone.setText(_("&No shortcut")) self.buttonCustom.setText(_("Use a &custom shortcut:")) for num in range(4): self.keylabels[num].setText(_("Alternative #{num}:").format(num=num) if num else _("Primary shortcut:")) def slotKeySequenceChanged(self): """Called when one of the keysequence buttons has changed.""" self.buttonCustom.setChecked(True) def editAction(self, action, default=None): # load the action self._action = action self._default = default self.toplabel.setText('<p>{0}</p>'.format( _("Here you can edit the shortcuts for {name}").format( name='<br/><b>{0}</b>:'.format(action.text())))) self.toppixmap.setPixmap(action.icon().pixmap(32)) shortcuts = action.shortcuts() self.buttonDefault.setVisible(default is not None) if default is not None and shortcuts == default: self.buttonDefault.setChecked(True) elif shortcuts: self.buttonCustom.setChecked(True) else: self.buttonNone.setChecked(True) for num, key in enumerate(shortcuts[:4]): self.keybuttons[num].setShortcut(key) for num in range(len(shortcuts), 4): self.keybuttons[num].clear() if default: ds = "; ".join(key.toString(QKeySequence.NativeText) for key in default) else: ds = _("no keyboard shortcut", "none") self.buttonDefault.setText(_("Use &default shortcut ({name})").format(name=ds)) return self.exec_() def done(self, result): if result: shortcuts = [] if self.buttonDefault.isChecked(): shortcuts = self._default elif self.buttonCustom.isChecked(): for num in range(4): seq = self.keybuttons[num].shortcut() if not seq.isEmpty(): shortcuts.append(seq) self._action.setShortcuts(shortcuts) super(ShortcutEditDialog, self).done(result)
class RunDialog(QDialog): """ Run parameters dialog implementation """ # See utils.run for runParameters def __init__(self, path, runParameters, termType, profilerParams, debuggerParams, action="", parent=None): QDialog.__init__(self, parent) # Used as a return value self.termType = termType self.profilerParams = copy.deepcopy(profilerParams) self.debuggerParams = copy.deepcopy(debuggerParams) self.__action = action.lower() # Avoid pylint complains self.__argsEdit = None self.__scriptWDRButton = None self.__dirRButton = None self.__dirEdit = None self.__dirSelectButton = None self.__inheritParentRButton = None self.__inheritParentPlusRButton = None self.__inhPlusEnvTable = None self.__addInhButton = None self.__delInhButton = None self.__editInhButton = None self.__specificRButton = None self.__specEnvTable = None self.__addSpecButton = None self.__delSpecButton = None self.__editSpecButton = None self.__runButton = None self.__nodeLimitEdit = None self.__edgeLimitEdit = None self.__createLayout(action) self.setWindowTitle(action + " parameters for " + path) # Restore the values self.runParams = copy.deepcopy(runParameters) self.__argsEdit.setText(self.runParams.arguments) # Working dir if self.runParams.useScriptLocation: self.__scriptWDRButton.setChecked(True) self.__dirEdit.setEnabled(False) self.__dirSelectButton.setEnabled(False) else: self.__dirRButton.setChecked(True) self.__dirEdit.setEnabled(True) self.__dirSelectButton.setEnabled(True) self.__dirEdit.setText(self.runParams.specificDir) # Environment self.__populateTable(self.__inhPlusEnvTable, self.runParams.additionToParentEnv) self.__populateTable(self.__specEnvTable, self.runParams.specificEnv) if self.runParams.envType == RunParameters.InheritParentEnv: self.__inheritParentRButton.setChecked(True) self.__setEnabledInheritedPlusEnv(False) self.__setEnabledSpecificEnv(False) elif self.runParams.envType == RunParameters.InheritParentEnvPlus: self.__inheritParentPlusRButton.setChecked(True) self.__setEnabledSpecificEnv(False) else: self.__specificRButton.setChecked(True) self.__setEnabledInheritedPlusEnv(False) # Terminal if self.termType == TERM_REDIRECT: self.__redirectRButton.setChecked(True) elif self.termType == TERM_AUTO: self.__autoRButton.setChecked(True) elif self.termType == TERM_KONSOLE: self.__konsoleRButton.setChecked(True) elif self.termType == TERM_GNOME: self.__gnomeRButton.setChecked(True) else: self.__xtermRButton.setChecked(True) # Close checkbox self.__closeCheckBox.setChecked(self.runParams.closeTerminal) if self.termType == TERM_REDIRECT: self.__closeCheckBox.setEnabled(False) # Profile limits if so if self.__action == "profile": if self.profilerParams.nodeLimit < 0.0 or \ self.profilerParams.nodeLimit > 100.0: self.profilerParams.nodeLimit = 1.0 self.__nodeLimitEdit.setText(str(self.profilerParams.nodeLimit)) if self.profilerParams.edgeLimit < 0.0 or \ self.profilerParams.edgeLimit > 100.0: self.profilerParams.edgeLimit = 1.0 self.__edgeLimitEdit.setText(str(self.profilerParams.edgeLimit)) elif self.__action == "debug": self.__reportExceptionCheckBox.setChecked( self.debuggerParams.reportExceptions) self.__traceInterpreterCheckBox.setChecked( self.debuggerParams.traceInterpreter) self.__stopAtFirstCheckBox.setChecked( self.debuggerParams.stopAtFirstLine) self.__autoforkCheckBox.setChecked(self.debuggerParams.autofork) self.__debugChildCheckBox.setChecked( self.debuggerParams.followChild) self.__debugChildCheckBox.setEnabled(self.debuggerParams.autofork) self.__setRunButtonProps() return @staticmethod def __populateTable(table, dictionary): " Populates the given table " for key, value in dictionary.iteritems(): item = QTreeWidgetItem([key, value]) table.addTopLevelItem(item) if dictionary: table.setCurrentItem(table.topLevelItem(0)) return def __setEnabledInheritedPlusEnv(self, value): " Disables/enables 'inherited and add' section controls " self.__inhPlusEnvTable.setEnabled(value) self.__addInhButton.setEnabled(value) self.__delInhButton.setEnabled(value) self.__editInhButton.setEnabled(value) return def __setEnabledSpecificEnv(self, value): " Disables/enables 'specific env' section controls " self.__specEnvTable.setEnabled(value) self.__addSpecButton.setEnabled(value) self.__delSpecButton.setEnabled(value) self.__editSpecButton.setEnabled(value) return def __createLayout(self, action): """ Creates the dialog layout """ self.resize(650, 300) self.setSizeGripEnabled(True) # Top level layout layout = QVBoxLayout(self) # Cmd line arguments argsLabel = QLabel("Command line arguments") self.__argsEdit = QLineEdit() self.__argsEdit.textChanged.connect(self.__argsChanged) argsLayout = QHBoxLayout() argsLayout.addWidget(argsLabel) argsLayout.addWidget(self.__argsEdit) layout.addLayout(argsLayout) # Working directory workDirGroupbox = QGroupBox(self) workDirGroupbox.setTitle("Working directory") sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( \ workDirGroupbox.sizePolicy().hasHeightForWidth() ) workDirGroupbox.setSizePolicy(sizePolicy) gridLayoutWD = QGridLayout(workDirGroupbox) self.__scriptWDRButton = QRadioButton(workDirGroupbox) self.__scriptWDRButton.setText("&Use script location") gridLayoutWD.addWidget(self.__scriptWDRButton, 0, 0) self.__scriptWDRButton.clicked.connect(self.__scriptWDirClicked) self.__dirRButton = QRadioButton(workDirGroupbox) self.__dirRButton.setText("Select &directory") gridLayoutWD.addWidget(self.__dirRButton, 1, 0) self.__dirRButton.clicked.connect(self.__dirClicked) self.__dirEdit = QLineEdit(workDirGroupbox) gridLayoutWD.addWidget(self.__dirEdit, 1, 1) self.__dirEdit.textChanged.connect(self.__workingDirChanged) self.__dirSelectButton = QPushButton(workDirGroupbox) self.__dirSelectButton.setText("...") gridLayoutWD.addWidget(self.__dirSelectButton, 1, 2) self.__dirSelectButton.clicked.connect(self.__selectDirClicked) layout.addWidget(workDirGroupbox) # Environment envGroupbox = QGroupBox(self) envGroupbox.setTitle("Environment") sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( \ envGroupbox.sizePolicy().hasHeightForWidth() ) envGroupbox.setSizePolicy(sizePolicy) layoutEnv = QVBoxLayout(envGroupbox) self.__inheritParentRButton = QRadioButton(envGroupbox) self.__inheritParentRButton.setText("Inherit &parent") self.__inheritParentRButton.clicked.connect(self.__inhClicked) layoutEnv.addWidget(self.__inheritParentRButton) self.__inheritParentPlusRButton = QRadioButton(envGroupbox) self.__inheritParentPlusRButton.setText( "Inherit parent and add/&modify") self.__inheritParentPlusRButton.clicked.connect(self.__inhPlusClicked) layoutEnv.addWidget(self.__inheritParentPlusRButton) hInhPlusLayout = QHBoxLayout() self.__inhPlusEnvTable = QTreeWidget() self.__inhPlusEnvTable.itemActivated.connect( self.__inhPlusItemActivated) self.__tuneTable(self.__inhPlusEnvTable) hInhPlusLayout.addWidget(self.__inhPlusEnvTable) vInhPlusLayout = QVBoxLayout() self.__addInhButton = QPushButton() self.__addInhButton.clicked.connect(self.__addInhClicked) self.__addInhButton.setText('Add') vInhPlusLayout.addWidget(self.__addInhButton) self.__delInhButton = QPushButton() self.__delInhButton.clicked.connect(self.__delInhClicked) self.__delInhButton.setText('Delete') vInhPlusLayout.addWidget(self.__delInhButton) self.__editInhButton = QPushButton() self.__editInhButton.clicked.connect(self.__editInhClicked) self.__editInhButton.setText("Edit") vInhPlusLayout.addWidget(self.__editInhButton) hInhPlusLayout.addLayout(vInhPlusLayout) layoutEnv.addLayout(hInhPlusLayout) self.__specificRButton = QRadioButton(envGroupbox) self.__specificRButton.setText("&Specific") self.__specificRButton.clicked.connect(self.__specClicked) layoutEnv.addWidget(self.__specificRButton) hSpecLayout = QHBoxLayout() self.__specEnvTable = QTreeWidget() self.__specEnvTable.itemActivated.connect(self.__specItemActivated) self.__tuneTable(self.__specEnvTable) hSpecLayout.addWidget(self.__specEnvTable) vSpecLayout = QVBoxLayout() self.__addSpecButton = QPushButton() self.__addSpecButton.clicked.connect(self.__addSpecClicked) self.__addSpecButton.setText('Add') vSpecLayout.addWidget(self.__addSpecButton) self.__delSpecButton = QPushButton() self.__delSpecButton.clicked.connect(self.__delSpecClicked) self.__delSpecButton.setText('Delete') vSpecLayout.addWidget(self.__delSpecButton) self.__editSpecButton = QPushButton() self.__editSpecButton.clicked.connect(self.__editSpecClicked) self.__editSpecButton.setText("Edit") vSpecLayout.addWidget(self.__editSpecButton) hSpecLayout.addLayout(vSpecLayout) layoutEnv.addLayout(hSpecLayout) layout.addWidget(envGroupbox) # Terminal and profile limits if self.__action in ["profile", "debug"]: layout.addWidget(self.__getIDEWideGroupbox()) else: termGroupbox = self.__getTermGroupbox() termGroupbox.setTitle("Terminal to run in (IDE wide setting)") layout.addWidget(termGroupbox) # Close checkbox self.__closeCheckBox = QCheckBox("&Close terminal upon " "successful completion") self.__closeCheckBox.stateChanged.connect(self.__onCloseChanged) layout.addWidget(self.__closeCheckBox) # Buttons at the bottom buttonBox = QDialogButtonBox(self) buttonBox.setOrientation(Qt.Horizontal) buttonBox.setStandardButtons(QDialogButtonBox.Cancel) self.__runButton = buttonBox.addButton(action, QDialogButtonBox.AcceptRole) self.__runButton.setDefault(True) self.__runButton.clicked.connect(self.onAccept) layout.addWidget(buttonBox) buttonBox.rejected.connect(self.close) return def __getTermGroupbox(self): " Creates the term groupbox " termGroupbox = QGroupBox(self) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( termGroupbox.sizePolicy().hasHeightForWidth()) termGroupbox.setSizePolicy(sizePolicy) layoutTerm = QVBoxLayout(termGroupbox) self.__redirectRButton = QRadioButton(termGroupbox) self.__redirectRButton.setText("&Redirect to IDE") self.__redirectRButton.toggled.connect(self.__redirectedChanged) layoutTerm.addWidget(self.__redirectRButton) self.__autoRButton = QRadioButton(termGroupbox) self.__autoRButton.setText("Aut&o detection") layoutTerm.addWidget(self.__autoRButton) self.__konsoleRButton = QRadioButton(termGroupbox) self.__konsoleRButton.setText("Default &KDE konsole") layoutTerm.addWidget(self.__konsoleRButton) self.__gnomeRButton = QRadioButton(termGroupbox) self.__gnomeRButton.setText("gnome-&terminal") layoutTerm.addWidget(self.__gnomeRButton) self.__xtermRButton = QRadioButton(termGroupbox) self.__xtermRButton.setText("&xterm") layoutTerm.addWidget(self.__xtermRButton) return termGroupbox def __redirectedChanged(self, checked): " Triggered when the redirected radio button changes its state " self.__closeCheckBox.setEnabled(not checked) return def __getIDEWideGroupbox(self): " Creates the IDE wide groupbox " ideGroupbox = QGroupBox(self) ideGroupbox.setTitle("IDE Wide Settings") sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( ideGroupbox.sizePolicy().hasHeightForWidth()) ideGroupbox.setSizePolicy(sizePolicy) layoutIDE = QHBoxLayout(ideGroupbox) termGroupbox = self.__getTermGroupbox() termGroupbox.setTitle("Terminal to run in") layoutIDE.addWidget(termGroupbox) if self.__action == "profile": # Profile version of the dialog limitsGroupbox = self.__getProfileLimitsGroupbox() layoutIDE.addWidget(limitsGroupbox) else: # Debug version of the dialog dbgGroupbox = self.__getDebugGroupbox() layoutIDE.addWidget(dbgGroupbox) return ideGroupbox def __getProfileLimitsGroupbox(self): " Creates the profile limits groupbox " limitsGroupbox = QGroupBox(self) limitsGroupbox.setTitle("Profiler diagram limits") sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( limitsGroupbox.sizePolicy().hasHeightForWidth()) limitsGroupbox.setSizePolicy(sizePolicy) layoutLimits = QGridLayout(limitsGroupbox) self.__nodeLimitEdit = QLineEdit() self.__nodeLimitEdit.textEdited.connect(self.__setRunButtonProps) self.__nodeLimitValidator = QDoubleValidator(0.0, 100.0, 2, self) self.__nodeLimitValidator.setNotation( QDoubleValidator.StandardNotation) self.__nodeLimitEdit.setValidator(self.__nodeLimitValidator) nodeLimitLabel = QLabel("Hide nodes below") self.__edgeLimitEdit = QLineEdit() self.__edgeLimitEdit.textEdited.connect(self.__setRunButtonProps) self.__edgeLimitValidator = QDoubleValidator(0.0, 100.0, 2, self) self.__edgeLimitValidator.setNotation( QDoubleValidator.StandardNotation) self.__edgeLimitEdit.setValidator(self.__edgeLimitValidator) edgeLimitLabel = QLabel("Hide edges below") layoutLimits.addWidget(nodeLimitLabel, 0, 0) layoutLimits.addWidget(self.__nodeLimitEdit, 0, 1) layoutLimits.addWidget(QLabel("%"), 0, 2) layoutLimits.addWidget(edgeLimitLabel, 1, 0) layoutLimits.addWidget(self.__edgeLimitEdit, 1, 1) layoutLimits.addWidget(QLabel("%"), 1, 2) return limitsGroupbox def __getDebugGroupbox(self): " Creates the debug settings groupbox " dbgGroupbox = QGroupBox(self) dbgGroupbox.setTitle("Debugger") sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( dbgGroupbox.sizePolicy().hasHeightForWidth()) dbgGroupbox.setSizePolicy(sizePolicy) dbgLayout = QVBoxLayout(dbgGroupbox) self.__reportExceptionCheckBox = QCheckBox("Report &exceptions") self.__reportExceptionCheckBox.stateChanged.connect( self.__onReportExceptionChanged) self.__traceInterpreterCheckBox = QCheckBox("T&race interpreter libs") self.__traceInterpreterCheckBox.stateChanged.connect( self.__onTraceInterpreterChanged) self.__stopAtFirstCheckBox = QCheckBox("Stop at first &line") self.__stopAtFirstCheckBox.stateChanged.connect( self.__onStopAtFirstChanged) self.__autoforkCheckBox = QCheckBox("&Fork without asking") self.__autoforkCheckBox.stateChanged.connect(self.__onAutoforkChanged) self.__debugChildCheckBox = QCheckBox("Debu&g child process") self.__debugChildCheckBox.stateChanged.connect(self.__onDebugChild) dbgLayout.addWidget(self.__reportExceptionCheckBox) dbgLayout.addWidget(self.__traceInterpreterCheckBox) dbgLayout.addWidget(self.__stopAtFirstCheckBox) dbgLayout.addWidget(self.__autoforkCheckBox) dbgLayout.addWidget(self.__debugChildCheckBox) return dbgGroupbox @staticmethod def __tuneTable(table): " Sets the common settings for a table " table.setAlternatingRowColors(True) table.setRootIsDecorated(False) table.setItemsExpandable(False) table.setUniformRowHeights(True) table.setSelectionMode(QAbstractItemView.SingleSelection) table.setSelectionBehavior(QAbstractItemView.SelectRows) table.setItemDelegate(NoOutlineHeightDelegate(4)) table.setHeaderLabels(["Variable", "Value"]) header = table.header() header.setSortIndicator(0, Qt.AscendingOrder) header.setSortIndicatorShown(True) header.setClickable(True) table.setSortingEnabled(True) return def __scriptWDirClicked(self): " The script working dir button is clicked " self.__dirEdit.setEnabled(False) self.__dirSelectButton.setEnabled(False) self.runParams.useScriptLocation = True self.__setRunButtonProps() return def __dirClicked(self): " The script specific working dir button is clicked " self.__dirEdit.setEnabled(True) self.__dirSelectButton.setEnabled(True) self.runParams.useScriptLocation = False self.__setRunButtonProps() return def __argsChanged(self, value): " Triggered when cmd line args are changed " value = str(value).strip() self.runParams.arguments = value self.__setRunButtonProps() return def __workingDirChanged(self, value): " Triggered when a working dir value is changed " value = str(value) self.runParams.specificDir = value self.__setRunButtonProps() return def __onCloseChanged(self, state): " Triggered when the close terminal check box changed " self.runParams.closeTerminal = state != 0 return def __onReportExceptionChanged(self, state): " Triggered when exception report check box changed " self.debuggerParams.reportExceptions = state != 0 return def __onTraceInterpreterChanged(self, state): " Triggered when trace interpreter changed " self.debuggerParams.traceInterpreter = state != 0 return def __onStopAtFirstChanged(self, state): " Triggered when stop at first changed " self.debuggerParams.stopAtFirstLine = state != 0 return def __onAutoforkChanged(self, state): " Triggered when autofork changed " self.debuggerParams.autofork = state != 0 self.__debugChildCheckBox.setEnabled(self.debuggerParams.autofork) return def __onDebugChild(self, state): " Triggered when debug child changed " self.debuggerParams.followChild = state != 0 return def __argumentsOK(self): " Returns True if the arguments are OK " try: parseCommandLineArguments(self.runParams.arguments) return True except: return False def __dirOK(self): " Returns True if the working dir is OK " if self.__scriptWDRButton.isChecked(): return True return os.path.isdir(self.__dirEdit.text()) def __setRunButtonProps(self, newText=None): " Enable/disable run button and set its tooltip " if not self.__argumentsOK(): self.__runButton.setEnabled(False) self.__runButton.setToolTip("No closing quotation in arguments") return if not self.__dirOK(): self.__runButton.setEnabled(False) self.__runButton.setToolTip("The given working " "dir is not found") return if self.__nodeLimitEdit is not None: txt = self.__nodeLimitEdit.text().strip() try: value = float(txt) if value < 0.0 or value > 100.0: raise Exception("Out of range") except: self.__runButton.setEnabled(False) self.__runButton.setToolTip("The given node limit " "is out of range") return if self.__edgeLimitEdit is not None: txt = self.__edgeLimitEdit.text().strip() try: value = float(txt) if value < 0.0 or value > 100.0: raise Exception("Out of range") except: self.__runButton.setEnabled(False) self.__runButton.setToolTip("The given edge limit " "is out of range") return self.__runButton.setEnabled(True) self.__runButton.setToolTip("Save parameters and " + self.__action + " script") return def __selectDirClicked(self): " Selects the script working dir " dirName = QFileDialog.getExistingDirectory( self, "Select the script working directory", self.__dirEdit.text(), QFileDialog.Options(QFileDialog.ShowDirsOnly)) if dirName: self.__dirEdit.setText(os.path.normpath(dirName)) return def __inhClicked(self): " Inerit parent env radio button clicked " self.__setEnabledInheritedPlusEnv(False) self.__setEnabledSpecificEnv(False) self.runParams.envType = RunParameters.InheritParentEnv return def __inhPlusClicked(self): " Inherit parent and add radio button clicked " self.__setEnabledInheritedPlusEnv(True) self.__setEnabledSpecificEnv(False) self.runParams.envType = RunParameters.InheritParentEnvPlus if self.__inhPlusEnvTable.selectedIndexes(): self.__delInhButton.setEnabled(True) self.__editInhButton.setEnabled(True) else: self.__delInhButton.setEnabled(False) self.__editInhButton.setEnabled(False) return def __specClicked(self): " Specific env radio button clicked " self.__setEnabledInheritedPlusEnv(False) self.__setEnabledSpecificEnv(True) self.runParams.envType = RunParameters.SpecificEnvironment if self.__specEnvTable.selectedIndexes(): self.__delSpecButton.setEnabled(True) self.__editSpecButton.setEnabled(True) else: self.__delSpecButton.setEnabled(False) self.__editSpecButton.setEnabled(False) return @staticmethod def __delAndInsert(table, name, value): " Deletes an item by name if so; insert new; highlight it " for index in xrange(table.topLevelItemCount()): item = table.topLevelItem(index) if str(item.text(0)) == name: table.takeTopLevelItem(index) break item = QTreeWidgetItem([name, value]) table.addTopLevelItem(item) table.setCurrentItem(item) return item def __addInhClicked(self): " Add env var button clicked " dlg = EnvVarDialog() if dlg.exec_() == QDialog.Accepted: name = str(dlg.name) value = str(dlg.value) self.__delAndInsert(self.__inhPlusEnvTable, name, value) self.runParams.additionToParentEnv[name] = value self.__delInhButton.setEnabled(True) self.__editInhButton.setEnabled(True) return def __addSpecClicked(self): " Add env var button clicked " dlg = EnvVarDialog() if dlg.exec_() == QDialog.Accepted: name = str(dlg.name) value = str(dlg.value) self.__delAndInsert(self.__specEnvTable, name, value) self.runParams.specificEnv[name] = value self.__delSpecButton.setEnabled(True) self.__editSpecButton.setEnabled(True) return def __delInhClicked(self): " Delete the highlighted variable " if self.__inhPlusEnvTable.topLevelItemCount() == 0: return name = self.__inhPlusEnvTable.currentItem().text(0) for index in xrange(self.__inhPlusEnvTable.topLevelItemCount()): item = self.__inhPlusEnvTable.topLevelItem(index) if name == item.text(0): self.__inhPlusEnvTable.takeTopLevelItem(index) break del self.runParams.additionToParentEnv[str(name)] if self.__inhPlusEnvTable.topLevelItemCount() == 0: self.__delInhButton.setEnabled(False) self.__editInhButton.setEnabled(False) else: self.__inhPlusEnvTable.setCurrentItem( \ self.__inhPlusEnvTable.topLevelItem( 0 ) ) return def __delSpecClicked(self): " Delete the highlighted variable " if self.__specEnvTable.topLevelItemCount() == 0: return name = self.__specEnvTable.currentItem().text(0) for index in xrange(self.__specEnvTable.topLevelItemCount()): item = self.__specEnvTable.topLevelItem(index) if name == item.text(0): self.__specEnvTable.takeTopLevelItem(index) break del self.runParams.specificEnv[str(name)] if self.__specEnvTable.topLevelItemCount() == 0: self.__delSpecButton.setEnabled(False) self.__editSpecButton.setEnabled(False) else: self.__specEnvTable.setCurrentItem( \ self.__specEnvTable.topLevelItem( 0 ) ) return def __editInhClicked(self): " Edits the highlighted variable " if self.__inhPlusEnvTable.topLevelItemCount() == 0: return item = self.__inhPlusEnvTable.currentItem() dlg = EnvVarDialog(str(item.text(0)), str(item.text(1)), self) if dlg.exec_() == QDialog.Accepted: name = str(dlg.name) value = str(dlg.value) self.__delAndInsert(self.__inhPlusEnvTable, name, value) self.runParams.additionToParentEnv[name] = value return def __inhPlusItemActivated(self, item, column): " Triggered when a table item is activated " self.__editInhClicked() return def __editSpecClicked(self): " Edits the highlighted variable " if self.__specEnvTable.topLevelItemCount() == 0: return item = self.__specEnvTable.currentItem() dlg = EnvVarDialog(str(item.text(0)), str(item.text(1)), self) if dlg.exec_() == QDialog.Accepted: name = str(dlg.name) value = str(dlg.value) self.__delAndInsert(self.__specEnvTable, name, value) self.runParams.specificEnv[name] = value return def __specItemActivated(self, item, column): " Triggered when a table item is activated " self.__editSpecClicked() return def onAccept(self): " Saves the selected terminal and profiling values " if self.__redirectRButton.isChecked(): self.termType = TERM_REDIRECT elif self.__autoRButton.isChecked(): self.termType = TERM_AUTO elif self.__konsoleRButton.isChecked(): self.termType = TERM_KONSOLE elif self.__gnomeRButton.isChecked(): self.termType = TERM_GNOME else: self.termType = TERM_XTERM if self.__action == "profile": self.profilerParams.nodeLimit = float(self.__nodeLimitEdit.text()) self.profilerParams.edgeLimit = float(self.__edgeLimitEdit.text()) self.accept() return
class FindInFilesDialog(QDialog, object): """ find in files dialog implementation """ inProject = 0 inDirectory = 1 inOpenFiles = 2 def __init__(self, where, what="", dirPath="", filters=[], parent=None): QDialog.__init__(self, parent) mainWindow = GlobalData().mainWindow self.editorsManager = mainWindow.editorsManagerWidget.editorsManager self.__cancelRequest = False self.__inProgress = False self.searchRegexp = None self.searchResults = [] # Avoid pylint complains self.findCombo = None self.caseCheckBox = None self.wordCheckBox = None self.regexpCheckBox = None self.projectRButton = None self.openFilesRButton = None self.dirRButton = None self.dirEditCombo = None self.dirSelectButton = None self.filterCombo = None self.fileLabel = None self.progressBar = None self.findButton = None self.__createLayout() self.setWindowTitle("Find in files") # Restore the combo box values project = GlobalData().project if project.fileName != "": self.findFilesWhat = project.findFilesWhat self.findFilesDirs = project.findFilesDirs self.findFilesMasks = project.findFilesMasks else: settings = Settings() self.findFilesWhat = settings.findFilesWhat self.findFilesDirs = settings.findFilesDirs self.findFilesMasks = settings.findFilesMasks self.findCombo.addItems(self.findFilesWhat) self.findCombo.setEditText("") self.dirEditCombo.addItems(self.findFilesDirs) self.dirEditCombo.setEditText("") self.filterCombo.addItems(self.findFilesMasks) self.filterCombo.setEditText("") if where == self.inProject: self.setSearchInProject(what, filters) elif where == self.inDirectory: self.setSearchInDirectory(what, dirPath, filters) else: self.setSearchInOpenFiles(what, filters) return def __createLayout(self): """ Creates the dialog layout """ self.resize(600, 300) self.setSizeGripEnabled(True) verticalLayout = QVBoxLayout(self) gridLayout = QGridLayout() # Combo box for the text to search findLabel = QLabel(self) findLabel.setText("Find text:") self.findCombo = QComboBox(self) self.__tuneCombo(self.findCombo) self.findCombo.lineEdit().setToolTip( "Regular expression to search for") self.findCombo.editTextChanged.connect(self.__someTextChanged) gridLayout.addWidget(findLabel, 0, 0, 1, 1) gridLayout.addWidget(self.findCombo, 0, 1, 1, 1) verticalLayout.addLayout(gridLayout) # Check boxes horizontalCBLayout = QHBoxLayout() self.caseCheckBox = QCheckBox(self) self.caseCheckBox.setText("Match &case") horizontalCBLayout.addWidget(self.caseCheckBox) self.wordCheckBox = QCheckBox(self) self.wordCheckBox.setText("Match whole &word") horizontalCBLayout.addWidget(self.wordCheckBox) self.regexpCheckBox = QCheckBox(self) self.regexpCheckBox.setText("Regular &expression") horizontalCBLayout.addWidget(self.regexpCheckBox) verticalLayout.addLayout(horizontalCBLayout) # Files groupbox filesGroupbox = QGroupBox(self) filesGroupbox.setTitle("Find in") sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( filesGroupbox.sizePolicy().hasHeightForWidth()) filesGroupbox.setSizePolicy(sizePolicy) gridLayoutFG = QGridLayout(filesGroupbox) self.projectRButton = QRadioButton(filesGroupbox) self.projectRButton.setText("&Project") gridLayoutFG.addWidget(self.projectRButton, 0, 0) self.projectRButton.clicked.connect(self.__projectClicked) self.openFilesRButton = QRadioButton(filesGroupbox) self.openFilesRButton.setText("&Opened files only") gridLayoutFG.addWidget(self.openFilesRButton, 1, 0) self.openFilesRButton.clicked.connect(self.__openFilesOnlyClicked) self.dirRButton = QRadioButton(filesGroupbox) self.dirRButton.setText("&Directory tree") gridLayoutFG.addWidget(self.dirRButton, 2, 0) self.dirRButton.clicked.connect(self.__dirClicked) self.dirEditCombo = QComboBox(filesGroupbox) self.__tuneCombo(self.dirEditCombo) self.dirEditCombo.lineEdit().setToolTip("Directory to search in") gridLayoutFG.addWidget(self.dirEditCombo, 2, 1) self.dirEditCombo.editTextChanged.connect(self.__someTextChanged) self.dirSelectButton = QPushButton(filesGroupbox) self.dirSelectButton.setText("...") gridLayoutFG.addWidget(self.dirSelectButton, 2, 2) self.dirSelectButton.clicked.connect(self.__selectDirClicked) filterLabel = QLabel(filesGroupbox) filterLabel.setText("Files filter:") gridLayoutFG.addWidget(filterLabel, 3, 0) self.filterCombo = QComboBox(filesGroupbox) self.__tuneCombo(self.filterCombo) self.filterCombo.lineEdit().setToolTip("File names regular expression") gridLayoutFG.addWidget(self.filterCombo, 3, 1) self.filterCombo.editTextChanged.connect(self.__someTextChanged) verticalLayout.addWidget(filesGroupbox) # File label self.fileLabel = FitPathLabel(self) self.fileLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed) verticalLayout.addWidget(self.fileLabel) # Progress bar self.progressBar = QProgressBar(self) self.progressBar.setValue(0) self.progressBar.setOrientation(Qt.Horizontal) verticalLayout.addWidget(self.progressBar) # Buttons at the bottom buttonBox = QDialogButtonBox(self) buttonBox.setOrientation(Qt.Horizontal) buttonBox.setStandardButtons(QDialogButtonBox.Cancel) self.findButton = buttonBox.addButton("Find", QDialogButtonBox.AcceptRole) self.findButton.setDefault(True) self.findButton.clicked.connect(self.__process) verticalLayout.addWidget(buttonBox) buttonBox.rejected.connect(self.__onClose) return @staticmethod def __tuneCombo(comboBox): " Sets the common settings for a combo box " sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( \ comboBox.sizePolicy().hasHeightForWidth() ) comboBox.setSizePolicy(sizePolicy) comboBox.setEditable(True) comboBox.setInsertPolicy(QComboBox.InsertAtTop) comboBox.setAutoCompletion(False) comboBox.setDuplicatesEnabled(False) return def __onClose(self): " Triggered when the close button is clicked " self.__cancelRequest = True if not self.__inProgress: self.close() return def setSearchInProject(self, what="", filters=[]): " Set search ready for the whole project " if GlobalData().project.fileName == "": # No project loaded, fallback to opened files self.setSearchInOpenFiles(what, filters) return # Select the project radio button self.projectRButton.setEnabled(True) self.projectRButton.setChecked(True) self.dirEditCombo.setEnabled(False) self.dirSelectButton.setEnabled(False) openedFiles = self.editorsManager.getTextEditors() self.openFilesRButton.setEnabled(len(openedFiles) != 0) self.setFilters(filters) self.findCombo.setEditText(what) self.findCombo.lineEdit().selectAll() self.findCombo.setFocus() # Check searchability self.__testSearchability() return def setSearchInOpenFiles(self, what="", filters=[]): " Sets search ready for the opened files " openedFiles = self.editorsManager.getTextEditors() if len(openedFiles) == 0: # No opened files, fallback to search in dir self.setSearchInDirectory(what, "", filters) return # Select the radio buttons self.projectRButton.setEnabled(GlobalData().project.fileName != "") self.openFilesRButton.setEnabled(True) self.openFilesRButton.setChecked(True) self.dirEditCombo.setEnabled(False) self.dirSelectButton.setEnabled(False) self.setFilters(filters) self.findCombo.setEditText(what) self.findCombo.lineEdit().selectAll() self.findCombo.setFocus() # Check searchability self.__testSearchability() return def setSearchInDirectory(self, what="", dirPath="", filters=[]): " Sets search ready for the given directory " # Select radio buttons self.projectRButton.setEnabled(GlobalData().project.fileName != "") openedFiles = self.editorsManager.getTextEditors() self.openFilesRButton.setEnabled(len(openedFiles) != 0) self.dirRButton.setEnabled(True) self.dirRButton.setChecked(True) self.dirEditCombo.setEnabled(True) self.dirSelectButton.setEnabled(True) self.dirEditCombo.setEditText(dirPath) self.setFilters(filters) self.findCombo.setEditText(what) self.findCombo.lineEdit().selectAll() self.findCombo.setFocus() # Check searchability self.__testSearchability() return def setFilters(self, filters): " Sets up the filters " # Set filters if provided if filters: self.filterCombo.setEditText(";".join(filters)) else: self.filterCombo.setEditText("") return def __testSearchability(self): " Tests the searchability and sets the Find button status " startTime = time.time() if self.findCombo.currentText().strip() == "": self.findButton.setEnabled(False) self.findButton.setToolTip("No text to search") return if self.dirRButton.isChecked(): dirname = self.dirEditCombo.currentText().strip() if dirname == "": self.findButton.setEnabled(False) self.findButton.setToolTip("No directory path") return if not os.path.isdir(dirname): self.findButton.setEnabled(False) self.findButton.setToolTip("Path is not a directory") return # Now we need to match file names if there is a filter filtersText = self.filterCombo.currentText().strip() if filtersText == "": self.findButton.setEnabled(True) self.findButton.setToolTip("Find in files") return # Need to check the files match try: filterRe = re.compile(filtersText, re.IGNORECASE) except: self.findButton.setEnabled(False) self.findButton.setToolTip( "Incorrect files " \ "filter regular expression" ) return matched = False tooLong = False if self.projectRButton.isChecked(): # Whole project for fname in GlobalData().project.filesList: if fname.endswith(sep): continue matched = filterRe.match(fname) if matched: break # Check the time, it might took too long if time.time() - startTime > 0.1: tooLong = True break elif self.openFilesRButton.isChecked(): # Opened files openedFiles = self.editorsManager.getTextEditors() for record in openedFiles: matched = filterRe.match(record[1]) if matched: break # Check the time, it might took too long if time.time() - startTime > 0.1: tooLong = True break else: # Search in the dir if not dirname.endswith(sep): dirname += sep matched, tooLong = self.__matchInDir(dirname, filterRe, startTime) if matched: self.findButton.setEnabled(True) self.findButton.setToolTip("Find in files") else: if tooLong: self.findButton.setEnabled(True) self.findButton.setToolTip("Find in files") else: self.findButton.setEnabled(False) self.findButton.setToolTip("No files matched to search in") return @staticmethod def __matchInDir(path, filterRe, startTime): " Provides the 'match' and 'too long' statuses " matched = False tooLong = False for item in os.listdir(path): if time.time() - startTime > 0.1: tooLong = True return matched, tooLong if os.path.isdir(path + item): dname = path + item + sep matched, tooLong = FindInFilesDialog.__matchInDir( dname, filterRe, startTime) if matched or tooLong: return matched, tooLong continue if filterRe.match(path + item): matched = True return matched, tooLong return matched, tooLong def __projectClicked(self): " project radio button clicked " self.dirEditCombo.setEnabled(False) self.dirSelectButton.setEnabled(False) self.__testSearchability() return def __openFilesOnlyClicked(self): " open files only radio button clicked " self.dirEditCombo.setEnabled(False) self.dirSelectButton.setEnabled(False) self.__testSearchability() return def __dirClicked(self): " dir radio button clicked " self.dirEditCombo.setEnabled(True) self.dirSelectButton.setEnabled(True) self.dirEditCombo.setFocus() self.__testSearchability() return def __someTextChanged(self, text): " Text to search, filter or dir name has been changed " self.__testSearchability() return def __selectDirClicked(self): " The user selects a directory " dirName = QFileDialog.getExistingDirectory( self, "Select directory to search in", self.dirEditCombo.currentText(), QFileDialog.Options(QFileDialog.ShowDirsOnly)) if dirName: self.dirEditCombo.setEditText(os.path.normpath(dirName)) self.__testSearchability() return def __projectFiles(self, filterRe): " Project files list respecting the mask " mainWindow = GlobalData().mainWindow files = [] for fname in GlobalData().project.filesList: if fname.endswith(sep): continue if filterRe is None or filterRe.match(fname): widget = mainWindow.getWidgetForFileName(fname) if widget is None: # Do not check for broken symlinks if isFileSearchable(fname, False): files.append(ItemToSearchIn(fname, "")) else: if widget.getType() in \ [ MainWindowTabWidgetBase.PlainTextEditor ]: files.append(ItemToSearchIn(fname, widget.getUUID())) QApplication.processEvents() if self.__cancelRequest: raise Exception("Cancel request") return files def __openedFiles(self, filterRe): " Currently opened editor buffers " files = [] openedFiles = self.editorsManager.getTextEditors() for record in openedFiles: uuid = record[0] fname = record[1] if filterRe is None or filterRe.match(fname): files.append(ItemToSearchIn(fname, uuid)) QApplication.processEvents() if self.__cancelRequest: raise Exception("Cancel request") return files def __dirFiles(self, path, filterRe, files): " Files recursively for the dir " for item in os.listdir(path): QApplication.processEvents() if self.__cancelRequest: raise Exception("Cancel request") if os.path.isdir(path + item): if item in [".svn", ".cvs"]: # It does not make sense to search in revision control dirs continue anotherDir, isLoop = resolveLink(path + item) if not isLoop: self.__dirFiles(anotherDir + sep, filterRe, files) continue if not os.path.isfile(path + item): continue realItem, isLoop = resolveLink(path + item) if isLoop: continue if filterRe is None or filterRe.match(realItem): found = False for itm in files: if itm.fileName == realItem: found = True break if not found: mainWindow = GlobalData().mainWindow widget = mainWindow.getWidgetForFileName(realItem) if widget is None: if isFileSearchable(realItem): files.append(ItemToSearchIn(realItem, "")) else: if widget.getType() in \ [ MainWindowTabWidgetBase.PlainTextEditor ]: files.append( ItemToSearchIn(realItem, widget.getUUID())) return def __buildFilesList(self): " Builds the list of files to search in " filtersText = self.filterCombo.currentText().strip() if filtersText != "": filterRe = re.compile(filtersText, re.IGNORECASE) else: filterRe = None if self.projectRButton.isChecked(): return self.__projectFiles(filterRe) if self.openFilesRButton.isChecked(): return self.__openedFiles(filterRe) dirname = os.path.realpath(self.dirEditCombo.currentText().strip()) files = [] self.__dirFiles(dirname + sep, filterRe, files) return files def __process(self): " Search process " # Add entries to the combo box if required regexpText = self.findCombo.currentText() if regexpText in self.findFilesWhat: self.findFilesWhat.remove(regexpText) self.findFilesWhat.insert(0, regexpText) if len(self.findFilesWhat) > 32: self.findFilesWhat = self.findFilesWhat[:32] self.findCombo.clear() self.findCombo.addItems(self.findFilesWhat) filtersText = self.filterCombo.currentText().strip() if filtersText in self.findFilesMasks: self.findFilesMasks.remove(filtersText) self.findFilesMasks.insert(0, filtersText) if len(self.findFilesMasks) > 32: self.findFilesMasks = self.findFilesMasks[:32] self.filterCombo.clear() self.filterCombo.addItems(self.findFilesMasks) if self.dirRButton.isChecked(): dirText = self.dirEditCombo.currentText().strip() if dirText in self.findFilesDirs: self.findFilesDirs.remove(dirText) self.findFilesDirs.insert(0, dirText) if len(self.findFilesDirs) > 32: self.findFilesDirs = self.findFilesDirs[:32] self.dirEditCombo.clear() self.dirEditCombo.addItems(self.findFilesDirs) # Save the combo values for further usage if GlobalData().project.fileName != "": GlobalData().project.setFindInFilesHistory(self.findFilesWhat, self.findFilesDirs, self.findFilesMasks) else: Settings().findFilesWhat = self.findFilesWhat Settings().findFilesDirs = self.findFilesDirs Settings().findFilesMasks = self.findFilesMasks self.__inProgress = True numberOfMatches = 0 self.searchResults = [] self.searchRegexp = None # Form the regexp to search if not self.regexpCheckBox.isChecked(): regexpText = re.escape(regexpText) if self.wordCheckBox.isChecked(): regexpText = "\\b%s\\b" % regexpText flags = re.UNICODE | re.LOCALE if not self.caseCheckBox.isChecked(): flags |= re.IGNORECASE try: self.searchRegexp = re.compile(regexpText, flags) except: logging.error("Invalid search expression") self.close() return QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.fileLabel.setPath('Building list of files to search in...') QApplication.processEvents() try: files = self.__buildFilesList() except Exception, exc: if "Cancel request" in str(exc): QApplication.restoreOverrideCursor() self.close() return else: QApplication.restoreOverrideCursor() logging.error(str(exc)) self.close() return QApplication.restoreOverrideCursor() QApplication.processEvents() if len(files) == 0: self.fileLabel.setPath('No files to search in') return self.progressBar.setRange(0, len(files)) index = 1 for item in files: if self.__cancelRequest: self.__inProgress = False self.close() return self.fileLabel.setPath( 'Matches: ' + str( numberOfMatches ) + \ ' Processing: ' + item.fileName ) item.search(self.searchRegexp) found = len(item.matches) if found > 0: numberOfMatches += found self.searchResults.append(item) self.progressBar.setValue(index) index += 1 QApplication.processEvents() if numberOfMatches == 0: if len(files) == 1: self.fileLabel.setPath("No matches in 1 file.") else: self.fileLabel.setPath( "No matches in " + \ str( len( files ) ) + " files." ) self.__inProgress = False else: self.close() return
class SessionForm(QDialog): pagetitle = 'Session Manager' def __init__(self, parent=None): super(SessionForm, self).__init__(parent) ko = 0 layout1 = QGridLayout() arr = self.pullClass() hold = {} for val in arr: self.num = val self.c = QRadioButton('cb' + str(val)) self.c.setText(str(arr[val][0])) self.c.setObjectName("chk" + str(val)) if (arr[val][3] == 1): self.c.setChecked(True) else: self.c.setChecked(False) self.c.toggled.connect( lambda state, x=val, y=self.c: self.chkFunc(x, y)) self.d = QLabel() sd = datetime.datetime.strptime(arr[val][1], '%Y-%m-%d').date() ed = datetime.datetime.strptime(arr[val][2], '%Y-%m-%d').date() sd = "{:%d, %b %Y}".format(sd) ed = "{:%d, %b %Y}".format(ed) self.d.setText(sd + ' - ' + ed) self.b = QPushButton() self.b.setObjectName("btn" + str(val)) self.b.setText('Terms') self.b1 = QPushButton() self.b1.setObjectName("btn1" + str(val)) self.b1.setText('Edit') hold["btn" + str(val)] = self.b hold["btnx" + str(val)] = self.b1 layout1.addWidget(self.c, ko, 0) layout1.addWidget(self.d, ko, 1) layout1.addWidget(self.b, ko, 2) layout1.addWidget(self.b1, ko, 3) ko += 1 for j in arr: self.h = j b = "btn" + str(j) b1 = "btnx" + str(j) self.connect(hold[b], SIGNAL("clicked()"), lambda gh=j: self.lunchUnitForm(gh, self)) self.connect(hold[b1], SIGNAL("clicked()"), lambda gh=j: self.lunchEditForm(gh, self)) groupBox1 = QGroupBox('All Sessions') groupBox1.setLayout(layout1) self.pb = QPushButton() self.pb.setObjectName("Add") self.pb.setText("Add Session") self.pb1 = QPushButton() self.pb1.setObjectName("Cancel") self.pb1.setText("Cancel") hbo = QHBoxLayout() hbo.addWidget(self.pb1) hbo.addStretch() hbo.addWidget(self.pb) groupBox2 = QGroupBox('') groupBox2.setLayout(hbo) grid = QGridLayout() grid.addWidget(groupBox1, 0, 0) grid.addWidget(groupBox2, 1, 0) self.setLayout(grid) self.connect(self.pb, SIGNAL("clicked()"), lambda: self.lunchAddForm(self)) self.connect(self.pb1, SIGNAL("clicked()"), lambda: self.button_close()) self.setWindowTitle(self.pagetitle) def chkFunc(self, a, b): # shost is a QString object self.a = a self.b = b g = Db() g.update('session', {'active': 0}, {'active': 1}) if b.isChecked() == True: y = {'active': 1} else: y = {'active': 0} z = {'id': self.a} j = g.update('session', y, z) return j def pullClass(self): cn = Db() students = cn.select('session', '', '') arr = {} try: for j in students: arr[j[0]] = [j[1], j[2], j[3], j[4]] except: pass return arr def lunchUnitForm(self, a, b): b.close() self.a = a form = TermForm(self.a) form.show() if form.exec_() == QDialog.Accepted: rtt = form.getValue() def lunchEditForm(self, a, b): b.close() self.a = a self.form = EditForm(self.a) self.form.show() def lunchAddForm(self, a): a.close() self.form = AddForm() self.form.show() def lunchForm(self): self.__init__() self.reloadSession() def button_close(self): self.close()
class UserMngForm(QDialog): def __init__(self, parent=None): QDialog.__init__(self) self.setObjectName(("ui_UserMngForm")) self.resize(200, 200) font = QFont() font.setFamily(("Arial")) font.setBold(False) font.setWeight(50) self.setFont(font) self.vlForm = QVBoxLayout(self) self.vlForm.setObjectName(("vl_UserMngForm")) self.vlForm.setSpacing(9) self.vlForm.setMargin(9) self.setWindowTitle("User Manage Dialog") self.basicFrame = Frame(self) self.vlForm.addWidget(self.basicFrame) self.userContentFrm = Frame(self.basicFrame, "HL") self.basicFrame.Add = self.userContentFrm self.groupbox = GroupBox(self.userContentFrm) self.groupbox.Caption = "Users" self.userContentFrm.Add = self.groupbox self.listBoxUser = ListBox(self.groupbox) self.groupbox.Add = self.listBoxUser self.userDataFrm = Frame(self.userContentFrm) self.userContentFrm.Add = self.userDataFrm self.groupBoxUserinfo = GroupBox(self.userDataFrm) self.groupBoxUserinfo.Caption = "User Information" self.userDataFrm.Add = self.groupBoxUserinfo self.userFullFrm = Frame(self.groupBoxUserinfo, "HL") self.groupBoxUserinfo.Add = self.userFullFrm self.textFirstName = TextBoxPanel(self.userFullFrm) self.textFirstName.Caption = "First Name" self.textFirstName.LabelWidth = 70 self.textFirstName.Width = 120 self.userFullFrm.Add = self.textFirstName self.textLastName = TextBoxPanel(self.userFullFrm) self.textLastName.Caption = "Last Name" self.textLastName.LabelWidth = 70 self.textLastName.Width = 120 self.userFullFrm.Add = self.textLastName self.userEmailPhoneFrm = Frame(self.groupBoxUserinfo, "HL") self.groupBoxUserinfo.Add = self.userEmailPhoneFrm self.textEMail = TextBoxPanel(self.userEmailPhoneFrm) self.textEMail.Caption = "E-Mail" self.textEMail.LabelWidth = 70 self.textEMail.Width = 120 self.userEmailPhoneFrm.Add = self.textEMail self.textPhone = TextBoxPanel(self.userEmailPhoneFrm) self.textPhone.Caption = "Phone" self.textPhone.LabelWidth = 70 self.textPhone.Width = 120 self.userEmailPhoneFrm.Add = self.textPhone self.userAddressCityFrm = Frame(self.groupBoxUserinfo, "HL") self.groupBoxUserinfo.Add = self.userAddressCityFrm self.textAddress = TextBoxPanel(self.userAddressCityFrm) self.textAddress.Caption = "Address" self.textAddress.LabelWidth = 70 self.textAddress.Width = 120 self.userAddressCityFrm.Add = self.textAddress self.textCity = TextBoxPanel(self.userAddressCityFrm) self.textCity.Caption = "City" self.textCity.LabelWidth = 70 self.textCity.Width = 120 self.userAddressCityFrm.Add = self.textCity self.userPostCodeStateFrm = Frame(self.groupBoxUserinfo, "HL") self.groupBoxUserinfo.Add = self.userPostCodeStateFrm self.textPostcode = TextBoxPanel(self.userPostCodeStateFrm) self.textPostcode.Caption = "Post Code" self.textPostcode.LabelWidth = 70 self.textPostcode.Width = 120 self.userPostCodeStateFrm.Add = self.textPostcode self.textState = TextBoxPanel(self.userPostCodeStateFrm) self.textState.Caption = "State" self.textState.LabelWidth = 70 self.textState.Width = 120 self.userPostCodeStateFrm.Add = self.textState self.groupBoxUserRoles = GroupBox(self.userDataFrm, "HL") self.groupBoxUserRoles.Caption = "User Roles" self.userDataFrm.Add = self.groupBoxUserRoles self.radioAdmin = QRadioButton(self.groupBoxUserRoles) self.radioAdmin.setObjectName("radioAdmin") self.radioAdmin.setText("Administrator") self.radioAdmin.setChecked(True) self.groupBoxUserRoles.Add = self.radioAdmin self.radioSuperuser = QRadioButton(self.groupBoxUserRoles) self.radioSuperuser.setObjectName("radioSuperuser") self.radioSuperuser.setText("Super User") self.groupBoxUserRoles.Add = self.radioSuperuser self.radioReadwrite = QRadioButton(self.groupBoxUserRoles) self.radioReadwrite.setObjectName("radioReadwrite") self.radioReadwrite.setText("Read / Write") self.groupBoxUserRoles.Add = self.radioReadwrite self.radioReadonly = QRadioButton(self.groupBoxUserRoles) self.radioReadonly.setObjectName("radioReadonly") self.radioReadonly.setText("Read Only") self.groupBoxUserRoles.Add = self.radioReadonly self.groupBoxUserDisplayInfo = GroupBox(self.userDataFrm, "HL") self.groupBoxUserDisplayInfo.Caption = "User Display Information" self.userDataFrm.Add = self.groupBoxUserDisplayInfo self.textName = TextBoxPanel(self.groupBoxUserDisplayInfo) self.textName.Caption = "Name" self.textName.LabelWidth = 70 self.textName.Width = 120 self.groupBoxUserDisplayInfo.Add = self.textName self.textPassword = TextBoxPanel(self.groupBoxUserDisplayInfo) self.textPassword.Caption = "Password" self.textPassword.LabelWidth = 70 self.textPassword.Width = 120 self.textPassword.EchoMode = "Password" self.groupBoxUserDisplayInfo.Add = self.textPassword self.btnFrame = Frame(self.basicFrame, "HL") self.basicFrame.Add = self.btnFrame self.buttonAddUser = QPushButton(self.btnFrame) self.buttonAddUser.setObjectName("buttonAddUser") self.buttonAddUser.setText("Add") self.btnFrame.Add = self.buttonAddUser self.buttonModifyUser = QPushButton(self.btnFrame) self.buttonModifyUser.setObjectName("buttonModifyUser") self.buttonModifyUser.setText("Modify") self.btnFrame.Add = self.buttonModifyUser self.buttonDeleteUser = QPushButton(self.btnFrame) self.buttonDeleteUser.setObjectName("buttonDeleteUser") self.buttonDeleteUser.setText("Delete") self.btnFrame.Add = self.buttonDeleteUser self.buttonSaveUser = QPushButton(self.btnFrame) self.buttonSaveUser.setObjectName("buttonSaveUser") self.buttonSaveUser.setText("Save") self.buttonSaveUser.setVisible(False) self.btnFrame.Add = self.buttonSaveUser self.buttonCloseUser = QPushButton(self.btnFrame) self.buttonCloseUser.setObjectName("buttonCloseProject") self.buttonCloseUser.setText("Close") self.btnFrame.Add = self.buttonCloseUser self.connect(self.listBoxUser, SIGNAL("Event_0"), self.listBoxUser_SelectedIndexChanged) self.buttonAddUser.clicked.connect(self.buttonAddUser_Click) self.buttonModifyUser.clicked.connect(self.buttonModifyUser_Click) self.buttonDeleteUser.clicked.connect(self.buttonDeleteUser_Click) self.buttonSaveUser.clicked.connect(self.buttonSaveUser_Click) self.buttonCloseUser.clicked.connect(self.buttonCloseUser_Click) for ui in AirCraftOperation.g_userList.ListUserInfo: self.listBoxUser.Add(ui.Name) def listBoxUser_SelectedIndexChanged(self): try: if (self.listBoxUser.SelectedIndex < 0): return selectedName = self.listBoxUser.Items[ self.listBoxUser.SelectedIndex] ui = AirCraftOperation.g_userList.FindUser(selectedName) if (ui.FName != None): self.textFirstName.Text = ui.FName else: self.textFirstName.Text = "" if (ui.LName != None): self.textLastName.Text = ui.LName else: self.textLastName.Text = "" if (ui.EMail != None): self.textEMail.Text = ui.EMail else: self.textEMail.Text = "" if (ui.Phone != None): self.textPhone.Text = ui.Phone else: self.textPhone.Text = "" if (ui.Address != None): self.textAddress.Text = ui.Address else: self.textAddress.Text = "" if (ui.PCode != None): self.textPostcode.Text = ui.PCode else: self.textPostcode.Text = "" if (ui.City != None): self.textCity.Text = ui.City else: self.textCity.Text = "" if (ui.State != None): self.textState.Text = ui.State else: self.textState.Text = "" if (ui.Name != None): self.textName.Text = ui.Name else: self.textName.Text = "" if (ui.Password != None): self.textPassword.Text = ui.Password else: self.textPassword.Text = "" if ui.Right == enumUserRight.ur_Admin: self.radioAdmin.setChecked(True) elif ui.Right == enumUserRight.ur_SuperUser: self.radioSuperuser.setChecked(True) elif ui.Right == enumUserRight.ur_ReadWrite: self.radioReadwrite.setChecked(True) elif ui.Right == enumUserRight.ur_ReadOnly: self.radioReadonly.setChecked(True) except: pass def buttonAddUser_Click(self): if (not self.CheckInputValues()): return newUser = self.SetUserInfo() if (AirCraftOperation.g_userList.AddUser(newUser)): self.listBoxUser.Add(newUser.Name) self.buttonSaveUser.Enabled = True def buttonModifyUser_Click(self): try: if (self.listBoxUser.SelectedIndex < 0): QMessageBox.warning( self, "Warning", "Please select an user in users list box!") if (not self.CheckInputValues()): return newUser = self.SetUserInfo() oldUser = AirCraftOperation.g_userList.FindUser( self.listBoxUser.Items[self.listBoxUser.SelectedIndex]) if (oldUser != None): AirCraftOperation.g_userList.DeleteUser(oldUser) AirCraftOperation.g_userList.AddUser(newUser) self.listBoxUser.Clear() for ui in AirCraftOperation.g_userList.ListUserInfo: self.listBoxUser.Add(ui.Name) self.buttonSaveUser.setEnabled(True) except: pass def buttonDeleteUser_Click(self): if (self.listBoxUser.SelectedIndex > -1): res = QMessageBox.question( self, "Question", "Do you want to delete this user information?", QMessageBox.Yes | QMessageBox.No) if (res == QMessageBox.No): return userName = self.listBoxUser.Items[self.listBoxUser.SelectedIndex] AirCraftOperation.g_userList.DeleteUser(userName) self.listBoxUser.Clear() for ui in AirCraftOperation.g_userList.ListUserInfo: self.listBoxUser.Add(ui.Name) AirCraftOperation.g_userList.WriteUserInfoFile() # self.buttonSaveUser.setEnabled(True) self.listBoxUser.SelectedIndex = self.listBoxUser.SelectedIndex - 1 if ( self.listBoxUser.SelectedIndex > 0) else 0 self.listBoxUser_SelectedIndexChanged() def buttonSaveUser_Click(self): if (self.buttonSaveUser.isEnabled() == True): res = QMessageBox.question(self, "Question", "Save changes to user information?", QMessageBox.Yes | QMessageBox.No) if (res == QMessageBox.Yes): AirCraftOperation.g_userList.WriteUserInfoFile() self.buttonSaveUser.setEnabled(False) def buttonCloseUser_Click(self): if (self.buttonSaveUser.isEnabled() == True): res = QMessageBox.question(self, "Question", "Save changes to user information?", QMessageBox.Yes | QMessageBox.No) if (res == QMessageBox.Yes): AirCraftOperation.g_userList.WriteUserInfoFile() self.buttonSaveUser.setEnabled(False) self.accept() def CheckInputValues(self): try: if (self.textFirstName.Text == ""): QMessageBox.warning( self, "Warning", "First name is required! Please input first name.") return False if (self.textLastName.Text == ""): QMessageBox.warning( self, "Warning", "Last name is required! Please input last name.") return False if (self.textName.Text == ""): QMessageBox.warning( self, "Warning", "Name is required! Please input display name.") return False return True except: return False def SetUserInfo(self): ui = MYUSERINFO() try: if (self.radioAdmin.isChecked()): ui.Right = enumUserRight.ur_Admin elif (self.radioSuperuser.isChecked()): ui.Right = enumUserRight.ur_SuperUser elif (self.radioReadwrite.isChecked()): ui.Right = enumUserRight.ur_ReadWrite elif (self.radioReadonly.isChecked()): ui.Right = enumUserRight.ur_ReadOnly if (self.textFirstName.Text != None): ui.FName = self.textFirstName.Text if (self.textFirstName.Text != None): ui.LName = self.textLastName.Text if (self.textFirstName.Text != None): ui.EMail = self.textEMail.Text if (self.textFirstName.Text != None): ui.Phone = self.textPhone.Text if (self.textFirstName.Text != None): ui.Address = self.textAddress.Text if (self.textFirstName.Text != None): ui.PCode = self.textPostcode.Text if (self.textFirstName.Text != None): ui.City = self.textCity.Text if (self.textFirstName.Text != None): ui.State = self.textState.Text if (self.textFirstName.Text != None): ui.Name = self.textName.Text if (self.textFirstName.Text != None): ui.Password = self.textPassword.Text return ui except: return None
class FindInFilesDialog( QDialog, object ): """ find in files dialog implementation """ inProject = 0 inDirectory = 1 inOpenFiles = 2 def __init__( self, where, what = "", dirPath = "", filters = [], parent = None ): QDialog.__init__( self, parent ) mainWindow = GlobalData().mainWindow self.editorsManager = mainWindow.editorsManagerWidget.editorsManager self.__cancelRequest = False self.__inProgress = False self.searchRegexp = None self.searchResults = [] # Avoid pylint complains self.findCombo = None self.caseCheckBox = None self.wordCheckBox = None self.regexpCheckBox = None self.projectRButton = None self.openFilesRButton = None self.dirRButton = None self.dirEditCombo = None self.dirSelectButton = None self.filterCombo = None self.fileLabel = None self.progressBar = None self.findButton = None self.__createLayout() self.setWindowTitle( "Find in files" ) # Restore the combo box values project = GlobalData().project if project.fileName != "": self.findFilesWhat = project.findFilesWhat self.findFilesDirs = project.findFilesDirs self.findFilesMasks = project.findFilesMasks else: settings = Settings() self.findFilesWhat = settings.findFilesWhat self.findFilesDirs = settings.findFilesDirs self.findFilesMasks = settings.findFilesMasks self.findCombo.addItems( self.findFilesWhat ) self.findCombo.setEditText( "" ) self.dirEditCombo.addItems( self.findFilesDirs ) self.dirEditCombo.setEditText( "" ) self.filterCombo.addItems( self.findFilesMasks ) self.filterCombo.setEditText( "" ) if where == self.inProject: self.setSearchInProject( what, filters ) elif where == self.inDirectory: self.setSearchInDirectory( what, dirPath, filters ) else: self.setSearchInOpenFiles( what, filters ) return def __createLayout( self ): """ Creates the dialog layout """ self.resize( 600, 300 ) self.setSizeGripEnabled( True ) verticalLayout = QVBoxLayout( self ) gridLayout = QGridLayout() # Combo box for the text to search findLabel = QLabel( self ) findLabel.setText( "Find text:" ) self.findCombo = QComboBox( self ) self.__tuneCombo( self.findCombo ) self.findCombo.lineEdit().setToolTip( "Regular expression to search for" ) self.findCombo.editTextChanged.connect( self.__someTextChanged ) gridLayout.addWidget( findLabel, 0, 0, 1, 1 ) gridLayout.addWidget( self.findCombo, 0, 1, 1, 1 ) verticalLayout.addLayout( gridLayout ) # Check boxes horizontalCBLayout = QHBoxLayout() self.caseCheckBox = QCheckBox( self ) self.caseCheckBox.setText( "Match &case" ) horizontalCBLayout.addWidget( self.caseCheckBox ) self.wordCheckBox = QCheckBox( self ) self.wordCheckBox.setText( "Match whole &word" ) horizontalCBLayout.addWidget( self.wordCheckBox ) self.regexpCheckBox = QCheckBox( self ) self.regexpCheckBox.setText( "Regular &expression" ) horizontalCBLayout.addWidget( self.regexpCheckBox ) verticalLayout.addLayout( horizontalCBLayout ) # Files groupbox filesGroupbox = QGroupBox( self ) filesGroupbox.setTitle( "Find in" ) sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred ) sizePolicy.setHorizontalStretch( 0 ) sizePolicy.setVerticalStretch( 0 ) sizePolicy.setHeightForWidth( filesGroupbox.sizePolicy().hasHeightForWidth() ) filesGroupbox.setSizePolicy( sizePolicy ) gridLayoutFG = QGridLayout( filesGroupbox ) self.projectRButton = QRadioButton( filesGroupbox ) self.projectRButton.setText( "&Project" ) gridLayoutFG.addWidget( self.projectRButton, 0, 0 ) self.projectRButton.clicked.connect( self.__projectClicked ) self.openFilesRButton = QRadioButton( filesGroupbox ) self.openFilesRButton.setText( "&Opened files only" ) gridLayoutFG.addWidget( self.openFilesRButton, 1, 0 ) self.openFilesRButton.clicked.connect( self.__openFilesOnlyClicked ) self.dirRButton = QRadioButton( filesGroupbox ) self.dirRButton.setText( "&Directory tree" ) gridLayoutFG.addWidget( self.dirRButton, 2, 0 ) self.dirRButton.clicked.connect( self.__dirClicked ) self.dirEditCombo = QComboBox( filesGroupbox ) self.__tuneCombo( self.dirEditCombo ) self.dirEditCombo.lineEdit().setToolTip( "Directory to search in" ) gridLayoutFG.addWidget( self.dirEditCombo, 2, 1 ) self.dirEditCombo.editTextChanged.connect( self.__someTextChanged ) self.dirSelectButton = QPushButton( filesGroupbox ) self.dirSelectButton.setText( "..." ) gridLayoutFG.addWidget( self.dirSelectButton, 2, 2 ) self.dirSelectButton.clicked.connect( self.__selectDirClicked ) filterLabel = QLabel( filesGroupbox ) filterLabel.setText( "Files filter:" ) gridLayoutFG.addWidget( filterLabel, 3, 0 ) self.filterCombo = QComboBox( filesGroupbox ) self.__tuneCombo( self.filterCombo ) self.filterCombo.lineEdit().setToolTip( "File names regular expression" ) gridLayoutFG.addWidget( self.filterCombo, 3, 1 ) self.filterCombo.editTextChanged.connect( self.__someTextChanged ) verticalLayout.addWidget( filesGroupbox ) # File label self.fileLabel = FitPathLabel( self ) self.fileLabel.setSizePolicy( QSizePolicy.Ignored, QSizePolicy.Fixed ) verticalLayout.addWidget( self.fileLabel ) # Progress bar self.progressBar = QProgressBar( self ) self.progressBar.setValue( 0 ) self.progressBar.setOrientation( Qt.Horizontal ) verticalLayout.addWidget( self.progressBar ) # Buttons at the bottom buttonBox = QDialogButtonBox( self ) buttonBox.setOrientation( Qt.Horizontal ) buttonBox.setStandardButtons( QDialogButtonBox.Cancel ) self.findButton = buttonBox.addButton( "Find", QDialogButtonBox.AcceptRole ) self.findButton.setDefault( True ) self.findButton.clicked.connect( self.__process ) verticalLayout.addWidget( buttonBox ) buttonBox.rejected.connect( self.__onClose ) return @staticmethod def __tuneCombo( comboBox ): " Sets the common settings for a combo box " sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Fixed ) sizePolicy.setHorizontalStretch( 0 ) sizePolicy.setVerticalStretch( 0 ) sizePolicy.setHeightForWidth( \ comboBox.sizePolicy().hasHeightForWidth() ) comboBox.setSizePolicy( sizePolicy ) comboBox.setEditable( True ) comboBox.setInsertPolicy( QComboBox.InsertAtTop ) comboBox.setAutoCompletion( False ) comboBox.setDuplicatesEnabled( False ) return def __onClose( self ): " Triggered when the close button is clicked " self.__cancelRequest = True if not self.__inProgress: self.close() return def setSearchInProject( self, what = "", filters = [] ): " Set search ready for the whole project " if GlobalData().project.fileName == "": # No project loaded, fallback to opened files self.setSearchInOpenFiles( what, filters ) return # Select the project radio button self.projectRButton.setEnabled( True ) self.projectRButton.setChecked( True ) self.dirEditCombo.setEnabled( False ) self.dirSelectButton.setEnabled( False ) openedFiles = self.editorsManager.getTextEditors() self.openFilesRButton.setEnabled( len( openedFiles ) != 0 ) self.setFilters( filters ) self.findCombo.setEditText( what ) self.findCombo.lineEdit().selectAll() self.findCombo.setFocus() # Check searchability self.__testSearchability() return def setSearchInOpenFiles( self, what = "", filters = [] ): " Sets search ready for the opened files " openedFiles = self.editorsManager.getTextEditors() if len( openedFiles ) == 0: # No opened files, fallback to search in dir self.setSearchInDirectory( what, "", filters ) return # Select the radio buttons self.projectRButton.setEnabled( GlobalData().project.fileName != "" ) self.openFilesRButton.setEnabled( True ) self.openFilesRButton.setChecked( True ) self.dirEditCombo.setEnabled( False ) self.dirSelectButton.setEnabled( False ) self.setFilters( filters ) self.findCombo.setEditText( what ) self.findCombo.lineEdit().selectAll() self.findCombo.setFocus() # Check searchability self.__testSearchability() return def setSearchInDirectory( self, what = "", dirPath = "", filters = [] ): " Sets search ready for the given directory " # Select radio buttons self.projectRButton.setEnabled( GlobalData().project.fileName != "" ) openedFiles = self.editorsManager.getTextEditors() self.openFilesRButton.setEnabled( len( openedFiles ) != 0 ) self.dirRButton.setEnabled( True ) self.dirRButton.setChecked( True ) self.dirEditCombo.setEnabled( True ) self.dirSelectButton.setEnabled( True ) self.dirEditCombo.setEditText( dirPath ) self.setFilters( filters ) self.findCombo.setEditText( what ) self.findCombo.lineEdit().selectAll() self.findCombo.setFocus() # Check searchability self.__testSearchability() return def setFilters( self, filters ): " Sets up the filters " # Set filters if provided if filters: self.filterCombo.setEditText( ";".join( filters ) ) else: self.filterCombo.setEditText( "" ) return def __testSearchability( self ): " Tests the searchability and sets the Find button status " startTime = time.time() if self.findCombo.currentText().strip() == "": self.findButton.setEnabled( False ) self.findButton.setToolTip( "No text to search" ) return if self.dirRButton.isChecked(): dirname = self.dirEditCombo.currentText().strip() if dirname == "": self.findButton.setEnabled( False ) self.findButton.setToolTip( "No directory path" ) return if not os.path.isdir( dirname ): self.findButton.setEnabled( False ) self.findButton.setToolTip( "Path is not a directory" ) return # Now we need to match file names if there is a filter filtersText = self.filterCombo.currentText().strip() if filtersText == "": self.findButton.setEnabled( True ) self.findButton.setToolTip( "Find in files" ) return # Need to check the files match try: filterRe = re.compile( filtersText, re.IGNORECASE ) except: self.findButton.setEnabled( False ) self.findButton.setToolTip( "Incorrect files " \ "filter regular expression" ) return matched = False tooLong = False if self.projectRButton.isChecked(): # Whole project for fname in GlobalData().project.filesList: if fname.endswith( sep ): continue matched = filterRe.match( fname ) if matched: break # Check the time, it might took too long if time.time() - startTime > 0.1: tooLong = True break elif self.openFilesRButton.isChecked(): # Opened files openedFiles = self.editorsManager.getTextEditors() for record in openedFiles: matched = filterRe.match( record[ 1 ] ) if matched: break # Check the time, it might took too long if time.time() - startTime > 0.1: tooLong = True break else: # Search in the dir if not dirname.endswith( sep ): dirname += sep matched, tooLong = self.__matchInDir( dirname, filterRe, startTime ) if matched: self.findButton.setEnabled( True ) self.findButton.setToolTip( "Find in files" ) else: if tooLong: self.findButton.setEnabled( True ) self.findButton.setToolTip( "Find in files" ) else: self.findButton.setEnabled( False ) self.findButton.setToolTip( "No files matched to search in" ) return @staticmethod def __matchInDir( path, filterRe, startTime ): " Provides the 'match' and 'too long' statuses " matched = False tooLong = False for item in os.listdir( path ): if time.time() - startTime > 0.1: tooLong = True return matched, tooLong if os.path.isdir( path + item ): dname = path + item + sep matched, tooLong = FindInFilesDialog.__matchInDir( dname, filterRe, startTime ) if matched or tooLong: return matched, tooLong continue if filterRe.match( path + item ): matched = True return matched, tooLong return matched, tooLong def __projectClicked( self ): " project radio button clicked " self.dirEditCombo.setEnabled( False ) self.dirSelectButton.setEnabled( False ) self.__testSearchability() return def __openFilesOnlyClicked( self ): " open files only radio button clicked " self.dirEditCombo.setEnabled( False ) self.dirSelectButton.setEnabled( False ) self.__testSearchability() return def __dirClicked( self ): " dir radio button clicked " self.dirEditCombo.setEnabled( True ) self.dirSelectButton.setEnabled( True ) self.dirEditCombo.setFocus() self.__testSearchability() return def __someTextChanged( self, text ): " Text to search, filter or dir name has been changed " self.__testSearchability() return def __selectDirClicked( self ): " The user selects a directory " dirName = QFileDialog.getExistingDirectory( self, "Select directory to search in", self.dirEditCombo.currentText(), QFileDialog.Options( QFileDialog.ShowDirsOnly ) ) if dirName: self.dirEditCombo.setEditText( os.path.normpath( dirName ) ) self.__testSearchability() return def __projectFiles( self, filterRe ): " Project files list respecting the mask " mainWindow = GlobalData().mainWindow files = [] for fname in GlobalData().project.filesList: if fname.endswith( sep ): continue if filterRe is None or filterRe.match( fname ): widget = mainWindow.getWidgetForFileName( fname ) if widget is None: # Do not check for broken symlinks if isFileSearchable( fname, False ): files.append( ItemToSearchIn( fname, "" ) ) else: if widget.getType() in \ [ MainWindowTabWidgetBase.PlainTextEditor ]: files.append( ItemToSearchIn( fname, widget.getUUID() ) ) QApplication.processEvents() if self.__cancelRequest: raise Exception( "Cancel request" ) return files def __openedFiles( self, filterRe ): " Currently opened editor buffers " files = [] openedFiles = self.editorsManager.getTextEditors() for record in openedFiles: uuid = record[ 0 ] fname = record[ 1 ] if filterRe is None or filterRe.match( fname ): files.append( ItemToSearchIn( fname, uuid ) ) QApplication.processEvents() if self.__cancelRequest: raise Exception( "Cancel request" ) return files def __dirFiles( self, path, filterRe, files ): " Files recursively for the dir " for item in os.listdir( path ): QApplication.processEvents() if self.__cancelRequest: raise Exception( "Cancel request" ) if os.path.isdir( path + item ): if item in [ ".svn", ".cvs" ]: # It does not make sense to search in revision control dirs continue anotherDir, isLoop = resolveLink( path + item ) if not isLoop: self.__dirFiles( anotherDir + sep, filterRe, files ) continue if not os.path.isfile( path + item ): continue realItem, isLoop = resolveLink( path + item ) if isLoop: continue if filterRe is None or filterRe.match( realItem ): found = False for itm in files: if itm.fileName == realItem: found = True break if not found: mainWindow = GlobalData().mainWindow widget = mainWindow.getWidgetForFileName( realItem ) if widget is None: if isFileSearchable( realItem ): files.append( ItemToSearchIn( realItem, "" ) ) else: if widget.getType() in \ [ MainWindowTabWidgetBase.PlainTextEditor ]: files.append( ItemToSearchIn( realItem, widget.getUUID() ) ) return def __buildFilesList( self ): " Builds the list of files to search in " filtersText = self.filterCombo.currentText().strip() if filtersText != "": filterRe = re.compile( filtersText, re.IGNORECASE ) else: filterRe = None if self.projectRButton.isChecked(): return self.__projectFiles( filterRe ) if self.openFilesRButton.isChecked(): return self.__openedFiles( filterRe ) dirname = os.path.realpath( self.dirEditCombo.currentText().strip() ) files = [] self.__dirFiles( dirname + sep, filterRe, files ) return files def __process( self ): " Search process " # Add entries to the combo box if required regexpText = self.findCombo.currentText() if regexpText in self.findFilesWhat: self.findFilesWhat.remove( regexpText ) self.findFilesWhat.insert( 0, regexpText ) if len( self.findFilesWhat ) > 32: self.findFilesWhat = self.findFilesWhat[ : 32 ] self.findCombo.clear() self.findCombo.addItems( self.findFilesWhat ) filtersText = self.filterCombo.currentText().strip() if filtersText in self.findFilesMasks: self.findFilesMasks.remove( filtersText ) self.findFilesMasks.insert( 0, filtersText ) if len( self.findFilesMasks ) > 32: self.findFilesMasks = self.findFilesMasks[ : 32 ] self.filterCombo.clear() self.filterCombo.addItems( self.findFilesMasks ) if self.dirRButton.isChecked(): dirText = self.dirEditCombo.currentText().strip() if dirText in self.findFilesDirs: self.findFilesDirs.remove( dirText ) self.findFilesDirs.insert( 0, dirText ) if len( self.findFilesDirs ) > 32: self.findFilesDirs = self.findFilesDirs[ : 32 ] self.dirEditCombo.clear() self.dirEditCombo.addItems( self.findFilesDirs ) # Save the combo values for further usage if GlobalData().project.fileName != "": GlobalData().project.setFindInFilesHistory( self.findFilesWhat, self.findFilesDirs, self.findFilesMasks ) else: Settings().findFilesWhat = self.findFilesWhat Settings().findFilesDirs = self.findFilesDirs Settings().findFilesMasks = self.findFilesMasks self.__inProgress = True numberOfMatches = 0 self.searchResults = [] self.searchRegexp = None # Form the regexp to search if not self.regexpCheckBox.isChecked(): regexpText = re.escape( regexpText ) if self.wordCheckBox.isChecked(): regexpText = "\\b%s\\b" % regexpText flags = re.UNICODE | re.LOCALE if not self.caseCheckBox.isChecked(): flags |= re.IGNORECASE try: self.searchRegexp = re.compile( regexpText, flags ) except: logging.error( "Invalid search expression" ) self.close() return QApplication.setOverrideCursor( QCursor( Qt.WaitCursor ) ) self.fileLabel.setPath( 'Building list of files to search in...' ) QApplication.processEvents() try: files = self.__buildFilesList() except Exception, exc: if "Cancel request" in str( exc ): QApplication.restoreOverrideCursor() self.close() return else: QApplication.restoreOverrideCursor() logging.error( str( exc ) ) self.close() return QApplication.restoreOverrideCursor() QApplication.processEvents() if len( files ) == 0: self.fileLabel.setPath( 'No files to search in' ) return self.progressBar.setRange( 0, len( files ) ) index = 1 for item in files: if self.__cancelRequest: self.__inProgress = False self.close() return self.fileLabel.setPath( 'Matches: ' + str( numberOfMatches ) + \ ' Processing: ' + item.fileName ) item.search( self.searchRegexp ) found = len( item.matches ) if found > 0: numberOfMatches += found self.searchResults.append( item ) self.progressBar.setValue( index ) index += 1 QApplication.processEvents() if numberOfMatches == 0: if len( files ) == 1: self.fileLabel.setPath( "No matches in 1 file." ) else: self.fileLabel.setPath( "No matches in " + \ str( len( files ) ) + " files." ) self.__inProgress = False else: self.close() return
class CompForm(QDialog): def __init__(self, sid, parent=None): super(CompForm, self).__init__(parent) self.sid = sid ko = 0 layout1 = QGridLayout() try: details = self.pullDetails(self.sid) pagetitle = str(details[1]) +' ' except: details = [] pagetitle = 'None' arr = self.pullClass(self.sid) hold ={} for val in arr: self.num = val self.c = QRadioButton('cb'+str(val)) self.c.setText(str(arr[val][0])) self.c.setObjectName("chk"+str(val)) if (arr[val][3] == 1): self.c.setChecked(True) else: self.c.setChecked(False) self.c.toggled.connect(lambda state, x=val, y=self.c: self.chkFunc(x, y)) self.d = QLabel() self.d.setText(arr[val][1] + ' - '+ arr[val][2]) self.b = QPushButton() self.b.setObjectName("btn"+str(val)) self.b.setText('Terms') self.b1 = QPushButton() self.b1.setObjectName("btn1"+str(val)) self.b1.setText('Edit') hold["btn"+str(val)] = self.b layout1.addWidget(self.c, ko, 0) layout1.addWidget(self.d, ko, 1) layout1.addWidget(self.b, ko, 2) ko += 1 for j in arr: self.h = j b = "btn"+str(j) self.connect(hold[b], SIGNAL("clicked()"), lambda gh=j: self.lunchEditForm(gh, self)) groupBox1 = QGroupBox('All Terms') groupBox1.setLayout(layout1) self.pb = QPushButton() self.pb.setObjectName("Add") self.pb.setText("Add Term") self.pb1 = QPushButton() self.pb1.setObjectName("Cancel") self.pb1.setText("Cancel") hbo = QHBoxLayout() hbo.addWidget(self.pb1) hbo.addStretch() hbo.addWidget(self.pb) groupBox2 = QGroupBox('') groupBox2.setLayout(hbo) grid = QGridLayout() grid.addWidget(groupBox1, 0, 0) grid.addWidget(groupBox2, 1, 0) self.setLayout(grid) self.connect(self.pb, SIGNAL("clicked()"), lambda: self.lunchAddForm(self.sid, self)) self.connect(self.pb1, SIGNAL("clicked()"), lambda: self.button_close(self)) self.setWindowTitle(pagetitle) def chkFunc(self, a, b): # shost is a QString object self.a = a self.b = b g = Db() g.update('datas', {'active':1}, {'active':0}) if b.isChecked() == True: y = { 'active':0} else: y = { 'active':1} z = {'id': self.a} j = g.update('datas', y, z) return j def pullClass(self, a): self.a = a cn = Db() cn.createData() datas = cn.select('datas', '' , '', {'subID':self.a}) arr = {} try: for j in datas: arr[j[0]] =[j[1], j[3], j[4], j[5]] except: pass return arr def pullDetails(self, a): self.a = a cn = Db() datas = cn.select('datas', '' , 1, {'id':self.a}) return datas def lunchEditForm(self, a, b): b.close() self.a = a self.form = EditForm(self.a) self.form.show() def lunchAddForm(self, a, b): b.close() self.a = a self.form = AddForm(self.a) self.form.show() def lunchForm(self): self.form = super.SubjectForm() self.form.show() def button_close(self, a): a.close() from frmsubject import SubjectForm self.form = SubjectForm() self.form.show()
class ShortcutEditDialog(QDialog): """A modal dialog to view and/or edit keyboard shortcuts.""" def __init__(self, parent=None, conflictCallback=None, *cbArgs): """conflictCallback is a optional method called when a shortcut is changed. cbArgs is optional arguments of the conflictCallback method. it should return the name of the potential conflict or a null value """ super(ShortcutEditDialog, self).__init__(parent) self.conflictCallback = conflictCallback self.cbArgs = cbArgs self.setMinimumWidth(400) # create gui layout = QVBoxLayout() layout.setSpacing(10) self.setLayout(layout) top = QHBoxLayout() top.setSpacing(4) p = self.toppixmap = QLabel() l = self.toplabel = QLabel() top.addWidget(p) top.addWidget(l, 1) layout.addLayout(top) grid = QGridLayout() grid.setSpacing(4) grid.setColumnStretch(1, 2) layout.addLayout(grid) self.buttonDefault = QRadioButton( self, toggled=self.slotButtonDefaultToggled) self.buttonNone = QRadioButton(self) self.lconflictDefault = QLabel('test') self.lconflictDefault.setStyleSheet("color : red;") self.lconflictDefault.setVisible(False) self.buttonCustom = QRadioButton(self) grid.addWidget(self.buttonDefault, 0, 0, 1, 2) grid.addWidget(self.lconflictDefault, 1, 0, 1, 2) grid.addWidget(self.buttonNone, 2, 0, 1, 2) grid.addWidget(self.buttonCustom, 3, 0, 1, 2) self.keybuttons = [] self.keylabels = [] self.conflictlabels = [] for num in range(4): l = QLabel(self) l.setStyleSheet("margin-left: 2em;") l.setAlignment(Qt.AlignRight | Qt.AlignVCenter) b = KeySequenceWidget(self, num) b.keySequenceChanged.connect(self.slotKeySequenceChanged) l.setBuddy(b) self.keylabels.append(l) self.keybuttons.append(b) grid.addWidget(l, num + 4 + num, 0) grid.addWidget(b, num + 4 + num, 1) lconflict = QLabel() lconflict.setStyleSheet("color : red;") self.conflictlabels.append(lconflict) lconflict.setVisible(False) grid.addWidget(lconflict, num + 5 + num, 0, 1, 2, Qt.AlignHCenter) layout.addWidget(Separator(self)) b = QDialogButtonBox(self) b.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) layout.addWidget(b) b.accepted.connect(self.accept) b.rejected.connect(self.reject) app.translateUI(self) def translateUI(self): self.setWindowTitle(app.caption(_("window title", "Edit Shortcut"))) self.buttonNone.setText(_("&No shortcut")) self.buttonCustom.setText(_("Use a &custom shortcut:")) for num in range(4): self.keylabels[num].setText( _("Alternative #{num}:").format( num=num) if num else _("Primary shortcut:")) def slotKeySequenceChanged(self, num): """Called when one of the keysequence buttons has changed.""" self.checkConflict(num) self.buttonCustom.setChecked(True) def slotButtonDefaultToggled(self, val): if self.conflictCallback is not None: if not val: self.lconflictDefault.setVisible(False) else: if self._default: conflictList = [] for s in self._default: conflictName = self.conflictCallback(s, *self.cbArgs) if conflictName: conflictList.append(conflictName) if conflictList: text = _("Conflict with: {name}").format( name="<b>{0}</b>".format(', '.join(conflictList))) self.lconflictDefault.setText(text) self.lconflictDefault.setVisible(True) QTimer.singleShot(0, self.adjustSize) def checkConflict(self, num): if self.conflictCallback is not None: conflictName = self.conflictCallback( self.keybuttons[num].shortcut(), *self.cbArgs) if conflictName: text = _("Conflict with: {name}").format( name="<b>{0}</b>".format(conflictName)) self.conflictlabels[num].setText(text) self.conflictlabels[num].setVisible(True) else: self.conflictlabels[num].setVisible(False) QTimer.singleShot(0, self.adjustSize) def editAction(self, action, default=None): # load the action self._action = action self._default = default self.toplabel.setText('<p>{0}</p>'.format( _("Here you can edit the shortcuts for {name}").format( name='<br/><b>{0}</b>:'.format(action.text())))) self.toppixmap.setPixmap(action.icon().pixmap(32)) shortcuts = action.shortcuts() self.buttonDefault.setVisible(bool(default)) if default is not None and shortcuts == default: self.buttonDefault.setChecked(True) else: if shortcuts: self.buttonCustom.setChecked(True) for num, key in enumerate(shortcuts[:4]): self.keybuttons[num].setShortcut(key) self.checkConflict(num) else: self.buttonNone.setChecked(True) if default: ds = "; ".join( key.toString(QKeySequence.NativeText) for key in default) else: ds = _("no keyboard shortcut", "none") self.buttonDefault.setText( _("Use &default shortcut ({name})").format(name=ds)) return self.exec_() def done(self, result): if result: shortcuts = [] if self.buttonDefault.isChecked(): shortcuts = self._default elif self.buttonCustom.isChecked(): for num in range(4): seq = self.keybuttons[num].shortcut() if not seq.isEmpty(): shortcuts.append(seq) self._action.setShortcuts(shortcuts) super(ShortcutEditDialog, self).done(result)
class Widget(QWidget): def __init__(self, dockwidget): super(Widget, self).__init__(dockwidget) self._document = None self._midiin = midiinput.MidiIn(self) self._dockwidget = weakref.ref(dockwidget) signals = list() self._labelmidichannel = QLabel() self._midichannel = QComboBox() signals.append(self._midichannel.currentIndexChanged) self._labelkeysignature = QLabel() self._keysignature = QComboBox() signals.append(self._keysignature.currentIndexChanged) self._labelaccidentals = QLabel() self._accidentalssharps = QRadioButton() signals.append(self._accidentalssharps.clicked) self._accidentalsflats = QRadioButton() signals.append(self._accidentalsflats.clicked) self._groupaccidentals = QGroupBox() self._groupaccidentals.setFlat(True) hbox = QHBoxLayout() self._groupaccidentals.setLayout(hbox) hbox.addWidget(self._accidentalssharps) hbox.addWidget(self._accidentalsflats) self._accidentalssharps.setChecked(True) self._chordmode = QCheckBox() signals.append(self._chordmode.clicked) self._relativemode = QCheckBox() signals.append(self._relativemode.clicked) self._labeldamper = QLabel() self._damper = QComboBox() self._labelsostenuto = QLabel() self._sostenuto = QComboBox() self._labelsoft = QLabel() self._soft = QComboBox() ac = self.parentWidget().actionCollection self._capture = QToolButton() self._capture.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) self._capture.setDefaultAction(ac.capture_start) self._notemode = QLabel() layout = QVBoxLayout() self.setLayout(layout) grid = QGridLayout(spacing=0) layout.addLayout(grid) grid.addWidget(self._labelmidichannel, 0, 0) grid.addWidget(self._midichannel, 0, 1) grid.addWidget(self._labelkeysignature, 1, 0) grid.addWidget(self._keysignature, 1, 1) grid.addWidget(self._labelaccidentals, 2, 0) grid.addWidget(self._groupaccidentals, 2, 1) grid.addWidget(self._chordmode, 3, 0) grid.addWidget(self._relativemode, 3, 1) grid.addWidget(self._labeldamper, 4, 0) grid.addWidget(self._damper, 4, 1) grid.addWidget(self._labelsostenuto, 5, 0) grid.addWidget(self._sostenuto, 5, 1) grid.addWidget(self._labelsoft, 6, 0) grid.addWidget(self._soft, 6, 1) hbox = QHBoxLayout() layout.addLayout(hbox) hbox.addWidget(self._capture) hbox.addStretch() app.translateUI(self) self.loadsettings() for s in signals: s.connect(self.savesettings) def mainwindow(self): return self._dockwidget().mainwindow() def channel(self): return self._midichannel.currentIndex() def keysignature(self): return self._keysignature.currentIndex() def accidentals(self): if self._accidentalsflats.isChecked(): return 'flats' else: return 'sharps' def chordmode(self): return self._chordmode.isChecked() def relativemode(self): return self._relativemode.isChecked() def startcapturing(self): self._midiin.capture() ac = self.parentWidget().actionCollection while self._capture.actions(): # remove all old actions self._capture.removeAction(self._capture.actions()[0]) self._capture.setDefaultAction(ac.capture_stop) def stopcapturing(self): self._midiin.capturestop() ac = self.parentWidget().actionCollection while self._capture.actions(): # remove all old actions self._capture.removeAction(self._capture.actions()[0]) self._capture.setDefaultAction(ac.capture_start) def savesettings(self): s = QSettings() s.beginGroup("midiinputdock") s.setValue("midichannel", self._midichannel.currentIndex()) s.setValue("keysignature", self._keysignature.currentIndex()) if self._accidentalsflats.isChecked(): s.setValue("accidentals", 'flats') else: s.setValue("accidentals", 'sharps') s.setValue("chordmode", self._chordmode.isChecked()) s.setValue("relativemode", self._relativemode.isChecked()) def loadsettings(self): s = QSettings() s.beginGroup("midiinputdock") self._midichannel.setCurrentIndex(s.value("midichannel", 0, int)) self._keysignature.setCurrentIndex(s.value("keysignature", 7, int)) if s.value("accidentals", 'sharps', str) == 'flats': self._accidentalsflats.setChecked(True) else: self._accidentalssharps.setChecked(True) self._chordmode.setChecked(s.value("chordmode", False, bool)) self._relativemode.setChecked(s.value("relativemode", False, bool)) def translateUI(self): self._labelmidichannel.setText(_("MIDI channel")) self._midichannel.addItems([_("all")]+[str(i) for i in range(1,17)]) self._labelkeysignature.setText(_("Key signature")) self._keysignature.addItems([ _("C flat major (7 flats)"), _("G flat major (6 flats)"), _("D flat major (5 flats)"), _("A flat major (4 flats)"), _("E flat major (3 flats)"), _("B flat major (2 flats)"), _("F major (1 flat)"), _("C major"), _("G major (1 sharp)"), _("D major (2 sharps)"), _("A major (3 sharps)"), _("E major (4 sharps)"), _("B major (5 sharps)"), _("F sharp major (6 sharps)"), _("C sharp major (7 sharps)") ]) self._keysignature.setCurrentIndex(7) self._labelaccidentals.setText(_("Accidentals")) self._accidentalssharps.setText(_("sharps")) self._accidentalsflats.setText(_("flats")) self._chordmode.setText(_("Chord mode")) self._chordmode.setToolTip(_( "Enter simultaneously played notes as chords. " "See \"What's This\" for more information.")) self._chordmode.setWhatsThis(_( "Notes which are played simultaneously are written " "as chords. As a consequence they are not written " "before the last key is lifted. Of course single " "can also be entered.")) self._relativemode.setText(_("Relative mode")) self._relativemode.setToolTip(_( "Enter octaves of notes relative to the last note. " "See \"What's This\" for more information.")) self._relativemode.setWhatsThis(_( "Enter octaves of notes relative to the last note. " "This refers to the last key pressed on the MIDI keyboard, not the last note in the document." "Hold Shift with a note to enter an octave check.")) self._labeldamper.setText(_("Damper pedal")) self._labelsostenuto.setText(_("Sostenuto pedal")) self._labelsoft.setText(_("Soft pedal"))
class GUI(QtGui.QMainWindow): def __init__(self, win_parent=None): ''' Initialize main window ''' QtGui.QMainWindow.__init__(self, win_parent) self.setWindowTitle('MapFormers: Get nodes geolocations') self.setGeometry(250, 200, 714, 491) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.setWindowFlags(Qt.CustomizeWindowHint) self.setWindowFlags(Qt.WindowSystemMenuHint) self.setWindowIcon(QtGui.QIcon(Paths["Icon"])) self.Elem_init() self.InitialValues() self.setGeometry_() self.InitialValues() self.setLabels() self.SetLayouts() if not CheckAttr(Visum.Net.Nodes, 'Google_X'): Visum.Net.Nodes.AddUserDefinedAttribute('Google_X', 'Google_X', 'Google_X', 2, 10) #else create UDAs if not CheckAttr(Visum.Net.Nodes, 'Google_Y'): Visum.Net.Nodes.AddUserDefinedAttribute('Google_Y', 'Google_Y', 'Google_Y', 2, 10) #else create UDAs self.connect(self.SB_NodeNumber, QtCore.SIGNAL('editingFinished()'), self.MakeVisScreenshot) self.connect(self.DSB_Zoom, QtCore.SIGNAL('editingFinished()'), self.MakeVisScreenshot) self.connect(self.SB_NodeNumber, QtCore.SIGNAL('editingFinished()'), self.UpdateGeoPos) self.connect(self.SB_NodeNumber, QtCore.SIGNAL('valueChanged()'), self.UpdateGeoPos) self.connect(self.B_ImportPos, QtCore.SIGNAL('clicked()'), self.ImportGeoPosition) self.connect(self.B_Next, QtCore.SIGNAL('clicked()'), self.NextWindow) self.connect(self.B_Back, QtCore.SIGNAL('clicked()'), self.BackWindow) self.connect(self.B_Calculate, QtCore.SIGNAL('clicked()'), self.Transform) self.connect(self.RB_prj, QtCore.SIGNAL('clicked()'), self.RBPrjClick) self.connect(self.RB_regression, QtCore.SIGNAL('clicked()'), self.RBRegClick) self.connect(self.RB_partiall, QtCore.SIGNAL('clicked()'), self.RBParClick) self.connect(self.B_Cancel, QtCore.SIGNAL('clicked()'), self.closeEvent) self.connect(self.B_Cancel_T2, QtCore.SIGNAL('clicked()'), self.closeEvent) self.connect(self.B_Help, QtCore.SIGNAL('clicked()'), self.openHelp) self.connect(self.B_Help_T2, QtCore.SIGNAL('clicked()'), self.openHelp) def Elem_init(self): self.SW_Main = QStackedWidget(self) self.SW_Tab1 = QWidget(self.SW_Main) self.SW_Tab2 = QWidget(self.SW_Main) self.GB_LeftSide = QGroupBox(self.SW_Tab1) self.GB_RightSide = QGroupBox(self.SW_Tab1) self.BottomWidget = QtGui.QWidget(self.SW_Tab1) self.Wid_LayVer_LeftSide = QtGui.QWidget(self.GB_LeftSide) self.L_ImageLeft = QtGui.QLabel(self.Wid_LayVer_LeftSide) self.GB_Options_LB = QtGui.QGroupBox(self.GB_LeftSide) self.L_NodeNumber = QtGui.QLabel(self.GB_Options_LB) self.L_zoom = QtGui.QLabel(self.GB_Options_LB) self.SB_NodeNumber = QtGui.QSpinBox(self.GB_Options_LB) self.DSB_Zoom = QtGui.QDoubleSpinBox(self.GB_Options_LB) self.L_GeoT = QtGui.QLabel(self.GB_Options_LB) self.L_GeoPos = QtGui.QLabel(self.GB_Options_LB) self.ImageLeft = QtGui.QPixmap(Paths["Screenshot"]) self.Wid_LayVer_RightSide = QtGui.QWidget(self.GB_RightSide) self.B_ImportPos = QtGui.QPushButton(self.Wid_LayVer_RightSide) self.Web = QWebView(self.Wid_LayVer_RightSide) self.B_Help = QtGui.QPushButton(self.BottomWidget) self.B_Next = QtGui.QPushButton(self.BottomWidget) self.B_Cancel = QtGui.QPushButton(self.BottomWidget) self.L_ImageLogo = QtGui.QLabel(self.BottomWidget) self.ImageLogo = QtGui.QPixmap(Paths["Logo"]) self.BG_Transform = QtGui.QGroupBox(self.SW_Tab2) self.BottomWidget_T2 = QtGui.QWidget(self.SW_Tab2) self.GB_Opt_T2 = QtGui.QGroupBox(self.SW_Tab2) self.SB_NodeNumber_T2 = QtGui.QSpinBox(self.GB_Opt_T2) self.DSB_Factor_T2 = QtGui.QDoubleSpinBox(self.GB_Opt_T2) self.L_Factor_T2 = QtGui.QLabel(self.GB_Opt_T2) self.L_NodeNumber_T2 = QtGui.QLabel(self.GB_Opt_T2) self.RB_prj = QRadioButton(self.BG_Transform) self.RB_regression = QRadioButton(self.BG_Transform) self.RB_partiall = QRadioButton(self.BG_Transform) self.B_Help_T2 = QtGui.QPushButton(self.BottomWidget_T2) self.B_Back = QtGui.QPushButton(self.BottomWidget_T2) self.B_Calculate = QtGui.QPushButton(self.BottomWidget_T2) self.B_Cancel_T2 = QtGui.QPushButton(self.BottomWidget_T2) self.L_ImageLogo_T2 = QtGui.QLabel(self.BottomWidget_T2) self.LayGrid_Main = QtGui.QGridLayout() self.LayVer_LeftSide = QtGui.QVBoxLayout() self.LayVer_RightSide = QtGui.QVBoxLayout() self.LayGrid_Bottom = QtGui.QGridLayout() self.LayGrid_Opt = QtGui.QGridLayout() self.LayVer_Main_T2 = QtGui.QVBoxLayout() self.Lay_Transform = QVBoxLayout() self.LayGrid_Bottom_T2 = QtGui.QGridLayout() self.BL_Lay_Transform = QtGui.QVBoxLayout() self.LayHor_Opt_T2 = QtGui.QHBoxLayout() self.V_NodeFilter = Visum.Filters.NodeFilter() self.V_LinkFilter = Visum.Filters.LinkFilter() def setLabels(self): self.GB_LeftSide.setTitle("Visum Node") self.GB_RightSide.setTitle("Map reference") self.L_NodeNumber.setText("Node number:") self.L_zoom.setText("Zoom:") self.L_GeoT.setText("Current node's geoposition:") self.L_GeoPos.setText("no reference") self.B_ImportPos.setText("Save reference") self.B_Help.setText("Help") self.B_Next.setText("Next ->") self.B_Cancel.setText("Cancel") self.RB_prj.setText( "Option 1: Transform network by means of .prj file.\n (This option will worn only if network scale is linear (scale for X axis = scale for Y axis) - \n in most cases it will not work for Your network." ) self.RB_regression.setText( "Option 2: Transform network by means of linear regression calibrated with input reference data. \n Specify confidence factor [0-1] for input data in the box below - default value is 0.8" ) self.RB_partiall.setText( "Option 3: Adjust only active part of the network (nodes, and links) based on reference node from box below" ) self.BG_Transform.setTitle("Transform network") self.B_Help_T2.setText("Help") self.B_Back.setText("<- Back") self.B_Calculate.setText("Calculate") self.B_Cancel_T2.setText("Cancel") self.L_Factor_T2.setText("Confidence factor:") self.L_NodeNumber_T2.setText("Node number:") def setGeometry_(self): self.B_Help.setFixedSize(85, 23) self.B_Next.setFixedSize(85, 23) self.B_Cancel.setFixedSize(85, 23) self.L_ImageLogo.setFixedSize(200, 32) self.B_Help_T2.setFixedSize(85, 23) self.B_Back.setFixedSize(85, 23) self.B_Calculate.setFixedSize(85, 23) self.B_Cancel_T2.setFixedSize(85, 23) self.L_ImageLogo_T2.setFixedSize(200, 32) self.L_ImageLeft.setMinimumSize(300, 300) self.L_ImageLeft.setBaseSize(350, 350) self.Web.setContentsMargins(0, 0, 0, 0) self.Web.setMinimumSize(350, 350) self.Web.setBaseSize(375, 375) def InitialValues(self): self.setCentralWidget(self.SW_Main) self.Web.page().mainFrame().load(QUrl(Paths["Html"])) self.Web.page().setViewportSize( self.Web.page().mainFrame().contentsSize()) NodeIter = Visum.Net.Nodes.Iterator try: FirstActiveNode = NodeIter.Item.AttValue("No") except: Visum.Net.AddNode(1, 1, 1) NodeIter = Visum.Net.Nodes.Iterator FirstActiveNode = NodeIter.Item.AttValue("No") Visum.Graphic.Autozoom(Visum.Net.Nodes.ItemByKey(FirstActiveNode)) self.V_NodeFilter.Init() self.V_NodeFilter.AddCondition("OP_NONE", False, "NO", "EqualVal", FirstActiveNode) self.V_NodeFilter.UseFilter = True self.V_LinkFilter.Init() self.V_LinkFilter.AddCondition("OP_NONE", False, "ToNodeNo", "EqualVal", FirstActiveNode) self.V_LinkFilter.UseFilter = True Visum.Graphic.Screenshot(Paths["Screenshot"]) Screenshot = QtGui.QPixmap(Paths["Screenshot"]) self.SB_NodeNumber.setValue(FirstActiveNode) self.SB_NodeNumber.setMaximum(1000000000) self.SB_NodeNumber_T2.setValue(FirstActiveNode) self.SB_NodeNumber_T2.setMaximum(1000000000) self.DSB_Factor_T2.setValue(0.8) self.DSB_Factor_T2.setMaximum(1) self.DSB_Zoom.setValue(1) self.DSB_Zoom.setSingleStep(0.5) self.DSB_Zoom.setMaximum(1000000) self.L_ImageLeft.setPixmap(Screenshot) self.L_ImageLeft.setScaledContents(True) self.ImageLogo.scaled(200, 23, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) #self.L_ImageLogo.setScaledContents(True) self.L_ImageLogo.setPixmap(self.ImageLogo) self.L_ImageLogo_T2.setScaledContents(True) self.L_ImageLogo_T2.setPixmap(self.ImageLogo) self.L_ImageLeft.show() self.RBRegClick() self.RB_regression.setChecked(True) def SetLayouts(self): self.L_NodeNumber.setAlignment(Qt.AlignVCenter | Qt.AlignRight) self.L_zoom.setAlignment(Qt.AlignVCenter | Qt.AlignRight) self.SB_NodeNumber.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) self.DSB_Zoom.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) self.L_GeoT.setAlignment(Qt.AlignVCenter | Qt.AlignRight) self.L_GeoPos.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) self.L_ImageLogo_T2.setAlignment(Qt.AlignVCenter | Qt.AlignHCenter) self.L_ImageLogo.setAlignment(Qt.AlignVCenter | Qt.AlignHCenter) self.L_NodeNumber_T2.setAlignment(Qt.AlignVCenter | Qt.AlignRight) self.SB_NodeNumber_T2.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) self.L_Factor_T2.setAlignment(Qt.AlignVCenter | Qt.AlignRight) self.DSB_Factor_T2.setAlignment(Qt.AlignVCenter | Qt.AlignLeft) self.GB_Options_LB.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.BottomWidget_T2.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.GB_Opt_T2.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.LayGrid_Opt.addWidget(self.L_NodeNumber, 1, 0, 1, 1) self.LayGrid_Opt.addWidget(self.L_zoom, 1, 2, 1, 1) self.LayGrid_Opt.addWidget(self.SB_NodeNumber, 1, 1, 1, 1) self.LayGrid_Opt.addWidget(self.DSB_Zoom, 1, 3, 1, 1) self.LayGrid_Opt.addWidget(self.L_GeoT, 0, 0, 1, 2) self.LayGrid_Opt.addWidget(self.L_GeoPos, 0, 2, 1, 2) self.LayGrid_Opt.setVerticalSpacing(20) self.LayVer_LeftSide.addWidget(self.L_ImageLeft) self.LayVer_LeftSide.addWidget(self.GB_Options_LB) self.LayVer_LeftSide.setSpacing(20) self.LayVer_RightSide.addWidget(self.Web) self.LayVer_RightSide.addWidget(self.B_ImportPos) self.LayVer_RightSide.setSpacing(20) self.LayGrid_Bottom.addWidget(self.B_Help, 0, 0, 1, 1) self.LayGrid_Bottom.addWidget(QWidget(), 0, 1, 1, 1) self.LayGrid_Bottom.addWidget(self.L_ImageLogo, 0, 2, 1, 1) self.LayGrid_Bottom.addWidget(QWidget(), 0, 3, 1, 1) self.LayGrid_Bottom.addWidget(self.B_Next, 0, 4, 1, 1) self.LayGrid_Bottom.addWidget(self.B_Cancel, 0, 5, 1, 1) self.LayGrid_Main.addWidget(self.GB_LeftSide, 0, 0, 1, 2) self.LayGrid_Main.addWidget(self.GB_RightSide, 0, 2, 1, 4) self.LayGrid_Main.addWidget(self.BottomWidget, 1, 0, 1, 6) self.BL_Lay_Transform.addWidget(self.RB_prj) self.BL_Lay_Transform.addWidget(self.RB_regression) self.BL_Lay_Transform.addWidget(self.RB_partiall) self.LayGrid_Bottom_T2.addWidget(self.B_Help_T2, 0, 0, 1, 1) self.LayGrid_Bottom_T2.addWidget(QWidget(), 0, 1, 1, 1) self.LayGrid_Bottom_T2.addWidget(self.L_ImageLogo_T2, 0, 2, 1, 1) self.LayGrid_Bottom_T2.addWidget(QWidget(), 0, 3, 1, 1) self.LayGrid_Bottom_T2.addWidget(self.B_Back, 0, 4, 1, 1) self.LayGrid_Bottom_T2.addWidget(self.B_Calculate, 0, 5, 1, 1) self.LayGrid_Bottom_T2.addWidget(self.B_Cancel_T2, 0, 6, 1, 1) self.LayHor_Opt_T2.addWidget(self.L_NodeNumber_T2) self.LayHor_Opt_T2.addWidget(self.SB_NodeNumber_T2) self.LayHor_Opt_T2.addWidget(self.L_Factor_T2) self.LayHor_Opt_T2.addWidget(self.DSB_Factor_T2) self.LayHor_Opt_T2.addWidget(QWidget()) self.LayVer_Main_T2.addWidget(self.BG_Transform) self.LayVer_Main_T2.addWidget(self.GB_Opt_T2) self.LayVer_Main_T2.addWidget(QWidget()) self.LayVer_Main_T2.addWidget(self.BottomWidget_T2) self.GB_Opt_T2.setLayout(self.LayHor_Opt_T2) self.SW_Main.addWidget(self.SW_Tab1) self.SW_Main.addWidget(self.SW_Tab2) self.GB_LeftSide.setLayout(self.LayVer_LeftSide) self.GB_RightSide.setLayout(self.LayVer_RightSide) self.GB_Options_LB.setLayout(self.LayGrid_Opt) self.BottomWidget.setLayout(self.LayGrid_Bottom) self.SW_Tab1.setLayout(self.LayGrid_Main) self.BG_Transform.setLayout(self.BL_Lay_Transform) self.BottomWidget_T2.setLayout(self.LayGrid_Bottom_T2) self.SW_Tab2.setLayout(self.LayVer_Main_T2) def RBPrjClick(self): self.DSB_Factor_T2.setDisabled(True) self.SB_NodeNumber_T2.setDisabled(True) def RBRegClick(self): self.DSB_Factor_T2.setEnabled(True) self.SB_NodeNumber_T2.setDisabled(True) def RBParClick(self): self.DSB_Factor_T2.setDisabled(True) self.SB_NodeNumber_T2.setEnabled(True) def NextWindow(self): self.SW_Main.setCurrentIndex(1) self.setWindowTitle('MapFormers: Transform network' ) #dodanie filtra na nodes - Google_X>0 self.V_NodeFilter.Init() self.V_NodeFilter.AddCondition("OP_NONE", False, "Google_X", 3, 0) self.V_NodeFilter.UseFilter = True def BackWindow(self): self.SW_Main.setCurrentIndex(0) self.setWindowTitle('MapFormers: Get nodes geolocations') def UpdateGeoPos(self): ''' Script updates label displaying node's geolocation ''' NodeNumber = self.SB_NodeNumber.value() try: xf = Visum.Net.Nodes.ItemByKey(NodeNumber).AttValue("Google_X") x = QString() x.setNum(xf, 'g', 5) yf = Visum.Net.Nodes.ItemByKey(NodeNumber).AttValue("Google_Y") y = QString() y.setNum(yf, 'g', 5) if (xf == 0 and yf == 0): self.Web.page().mainFrame().evaluateJavaScript( "removemarkers();") self.L_GeoPos.setText("no reference") else: self.L_GeoPos.setText("x: " + x + " N" + " y: " + y + " E") self.Web.page().mainFrame().evaluateJavaScript( "Gx = %f; Gy = %f;" % (xf, yf)) self.Web.page().mainFrame().evaluateJavaScript("markerf();") except: self.L_GeoPos.setText("node does not exist") def ImportGeoPosition(self): ''' evaluate JavaScript to return previously selected geographical position in OpenLayers WebWidget ''' NodeNumber = self.SB_NodeNumber.value() try: Visum.Net.Nodes.GetMultiAttValues( 'Google_X') #check if UDAs exists except: Visum.Net.Nodes.AddUserDefinedAttribute('Google_X', 'Google_X', 'Google_X', 2, 10) #else create UDAs Visum.Net.Nodes.AddUserDefinedAttribute('Google_Y', 'Google_Y', 'Google_Y', 2, 10) Visum.Net.Nodes.ItemByKey(NodeNumber).SetAttValue( "Google_X", self.Web.page().mainFrame().evaluateJavaScript( "returnposx();").toReal()[0] ) # w pliku html trzeba sie upewnic, ze to zawsze bedzie wspolrzedna lon/lat ! ! ! czasami osm samo zmienia na Projected Coordinate System (czyli wartosci okolo miliona, tak nie moze byc, bo nigdy nie dojdziemy do ladu!zawsze musza byc lon/lat Visum.Net.Nodes.ItemByKey(NodeNumber).SetAttValue( "Google_Y", self.Web.page().mainFrame().evaluateJavaScript( "returnposy();").toReal()[0]) self.UpdateGeoPos() def Transform(self): type = [ self.RB_prj.isChecked(), False, self.RB_regression.isChecked(), self.RB_partiall.isChecked() ] nodeno = self.SB_NodeNumber_T2.value() factor = self.DSB_Factor_T2.value() def rescale(scaleX, scaleY, deltaX, deltaY, activeOnly): def link_iter(): def New_WKT(WKT, scaleX, scaleY, deltaX, deltaY): WKT = str(WKT[11:-1]) WKT = WKT.split(',') for i in range(len(WKT)): WKT[i] = WKT[i].split(' ') WKT = [[i for i in el] for el in WKT] del WKT[0] del WKT[-1] Mtx = [[ scaleX * float(el[0]) + deltaX, scaleY * float(el[1]) + deltaY ] for el in WKT] Nowy = [[float(el[0]), float(el[1])] for el in Mtx] Nowy = ', '.join([str(x) for x in Nowy]) Nowy = Nowy.replace('],', 'www') Nowy = Nowy.replace(',', '') Nowy = Nowy.replace('www', ',') Nowy = Nowy.replace('[', '') Nowy = Nowy.replace(']', '') Nowy = 'LINESTRING(' + Nowy + ')' return Nowy Container = Visum.Net.Links WKTs = Container.GetMultiAttValues('WKTPOLY', activeOnly) New_WKTs = [] for i in range(len(WKTs)): New_WKTs.append((WKTs[i][0], New_WKT(WKTs[i][1], scaleX, scaleY, deltaX, deltaY))) return tuple(New_WKTs) def iter(Container): Xy = Container.GetMultiAttValues('XCoord', activeOnly) Yy = Container.GetMultiAttValues('YCoord', activeOnly) New_Xy = [] New_Yy = [] for i in range(len(Xy)): New_Xy.append((Xy[i][0], scaleX * Xy[i][1] + deltaX)) New_Yy.append((Yy[i][0], scaleY * Yy[i][1] + deltaY)) return tuple(New_Xy), tuple(New_Yy) Container.SetMultiAttValues('XCoord', tuple(New_Xy)) Container.SetMultiAttValues('YCoord', tuple(New_Yy)) Node_X, Node_Y = iter(Visum.Net.Nodes) New_WKTs = link_iter() Zone_X, Zone_Y = iter(Visum.Net.Zones) #Visum.Graphic.ShowMinimized() Visum.Net.Nodes.SetMultiAttValues('XCoord', Node_X) Visum.Net.Nodes.SetMultiAttValues('YCoord', Node_Y) try: Visum.Net.Links.SetMultiAttValues('WKTPOLY', New_WKTs) except: pass try: Visum.Net.Zones.SetMultiAttValues('XCoord', Zone_X) Visum.Net.Zones.SetMultiAttValues('YCoord', Zone_Y) except: pass def get_wgs(X): #transform google lon lat to X,Y from pyproj import Proj pr_tm = Proj( '+proj=merc +lat_0=0 +lon_0=0 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs' ) x_latlong = X[0] y_latlong = X[1] x_tm, y_tm = pr_tm(X[0], X[1]) return x_tm, y_tm def set_Visum_projection(false_easting, false_northing, scale): scale = 1 / float( scale) #""" reciprocal of scale correct effect """ Visum_Projection = u'PROJCS["Mapformers",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["GRS_1980",6378137.0,298.257223562]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Mercator"],PARAMETER["False_Easting",' + str( false_easting ) + ' ],PARAMETER["False_Northing",' + str( false_northing ) + ' ],PARAMETER["Central_Meridian",0],PARAMETER["Standard_Parallel_1",0],UNIT["Meter",' + str( scale) + ']]' Visum.Net.NetParameters.SetProjection(Visum_Projection, True) def get_coords(): Visum_X = Visum.Net.Nodes.GetMultiAttValues('XCoord', True) Visum_X = [el[1] for el in Visum_X] Visum_Y = Visum.Net.Nodes.GetMultiAttValues('YCoord', True) Visum_Y = [el[1] for el in Visum_Y] Google_X = Visum.Net.Nodes.GetMultiAttValues('Google_X', True) Google_X = [el[1] for el in Google_X] Google_Y = Visum.Net.Nodes.GetMultiAttValues('Google_Y', True) Google_Y = [el[1] for el in Google_Y] #if Google_X[0]<200: # for i in range(len(Google_X)): # point=[Google_X[i],Google_Y[i]] # [Google_X[i],Google_Y[i]]=get_wgs(point) return Visum_X, Visum_Y, Google_X, Google_Y def linreg(Visum_, Google_): try: numpy except: import numpy as np (scale, delta) = np.polyfit(Visum_, Google_, 1) nGoogle_ = np.polyval([scale, delta], Visum_) err = (sum((nGoogle_ - Google_)**2) / len(Visum_))**.5 return scale, delta, err def cleaned_linreg(Visum_, Google_, cut_factor): try: numpy except: import numpy as np errs = [] cut_factor = min((max(cut_factor, .1)), 1) range_ = range(max(1, int(len(Google_) * cut_factor))) for j in range_: (scale, delta) = np.polyfit(Visum_, Google_, 1) nGoogle_ = np.polyval([scale, delta], Visum_) err = [(nGoogle_[i] - Google_[i])**2 for i in range(len(nGoogle_))] errs.append((sum((nGoogle_ - Google_)**2) / len(Visum_))**.5) max_err = err.index(max(err)) Visum_.remove(Visum_[max_err]) Google_.remove(Google_[max_err]) return scale, delta, errs def dist(X, Y): return ((X[0] - X[1])**2 + (Y[0] - Y[1])**2)**.5 def do_projection(Visum_X, Visum_Y, Google_X, Google_Y): dist_Visum = dist( Visum_X, Visum_Y ) #"""calculate distance in Visum, and real distance in Google""" dist_Google = dist(Google_X, Google_Y) scale = dist_Google / dist_Visum set_Visum_projection( 0, 0, 1) #"""first set base projection with scale =1""" set_Visum_projection(0, 0, scale) #"""now adjust the scale""" Visum_X = Visum.Net.Nodes.GetMultiAttValues('XCoord', True) Visum_X = [el[1] for el in Visum_X] Visum_Y = Visum.Net.Nodes.GetMultiAttValues('YCoord', True) Visum_Y = [el[1] for el in Visum_Y] #"""get new rescaled coords""" delta_X = Google_X[0] - Visum_X[0] delta_Y = Google_Y[0] - Visum_Y[0] set_Visum_projection( 0, 0, 1) #"""first set base projection with scale = 1""" set_Visum_projection(0, 0, scale) #"""now adjust the scale""" set_Visum_projection( 0, 0, 1) #"""now set bas projection one more time""" set_Visum_projection(delta_X, delta_Y, scale) #"""and go to proper projection""" def analyse_Coords(Visum_X, Visum_Y, Google_X, Google_Y): def dst_mtx(A, *B): try: B mtx = [[abs(a - b) for a in A] for b in B] except: mtx = [[abs(a - b) for a in A] for b in A] return mtx def get_scale(Visum_d, Google_d): range_ = range(len(Visum_d)) Visum_deltas = dst_mtx(Visum_d) for i in range_: for j in range_: if i == j: Visum_deltas[i][i] = 1000000000000000000000 Google_deltas = dst_mtx(Google_d) scales = [[ Google_deltas[i][j] / Visum_deltas[i][j] for i in range_ ] for j in range_] return sum([sum(row) for row in scales ]) / (len(Visum_d)**2 - len(Visum_d)) def get_delta(Visum_d, Google_d, scale): size = len(Visum_d) return -sum( [Visum_d[i] * scale - Google_d[i] for i in range(size)]) / float(size) def get_tg_Mtx(Visum_X, Visum_Y, Google_X, Google_Y): # to do ! dla macierzy obliczyc tg nachylenia par punktow dla Googla i dla Visuma # policzyc roznice miedzy katami i statycznie opisac (mean, std, dev, etc.) pass scale_X = get_scale(Visum_X, Google_X) scale_Y = get_scale(Visum_Y, Google_Y) delta_X = get_delta(Visum_X, Google_X, scale_X) delta_Y = get_delta(Visum_Y, Google_Y, scale_Y) return scale_X, scale_Y, delta_X, delta_Y #tg_V=abs(Visum_X[0]-Visum_X[1])/abs(Visum_Y[0]-Visum_Y[1]) #tg_G=abs(Google_X[0]-Google_X[1])/abs(Google_Y[0]-Google_Y[1]) #dev=1-tg_V/tg_G Visum_X, Visum_Y, Google_X, Google_Y = get_coords() Visum.Graphic.ShowMinimized() if type == [1, 0, 0, 0]: """ poprzez projekcje Visum set projection """ do_projection(Visum_X, Visum_Y, Google_X, Google_Y) elif type == [0, 1, 0, 0]: """ przypadek rescale dla dwu punktow """ scale_X, scale_Y, delta_X, delta_Y = analyse_Coords( Visum_X, Visum_Y, Google_X, Google_Y) rescale(scale_X, scale_Y, delta_X, delta_Y, False) elif type == [0, 0, 1, 0]: """ przypadek rescale dla wielu punktow """ scale_X, delta_X, _ = cleaned_linreg( Visum_X, Google_X, factor) #zmiana 0,8 -> factor. scale_Y, delta_Y, _ = cleaned_linreg(Visum_Y, Google_Y, factor) rescale(scale_X, scale_Y, delta_X, delta_Y, False) else: """ przesuniecie czesci sieci (dodatkowy tuning) """ Node = Visum.Net.Nodes.ItemByKey(nodeno) delta_X = Node.AttValue('Google_X') - Node.AttValue('XCoord') delta_Y = Node.AttValue('Google_Y') - Node.AttValue('YCoord') rescale(1, 1, delta_X, delta_Y, True) Visum.Graphic.ShowMaximized() #"""finito""" def MakeVisScreenshot(self): ''' make the screenshot of visum network with selected options ''' NodeNumber = self.SB_NodeNumber.value() zoom = self.DSB_Zoom.value() try: zoom = 1 / zoom except: pass try: Visum.Graphic.Autozoom(Visum.Net.Nodes.ItemByKey(NodeNumber)) self.V_NodeFilter.Init() self.V_NodeFilter.AddCondition("OP_NONE", False, "NO", "EqualVal", NodeNumber) self.V_NodeFilter.UseFilter = True self.V_LinkFilter.Init() self.V_LinkFilter.AddCondition("OP_NONE", False, "ToNodeNo", "EqualVal", NodeNumber) self.V_LinkFilter.UseFilter = True Window = Visum.Graphic.GetWindow() WWidth = Window[2] - Window[0] WHeight = Window[3] - Window[1] WXCenter = Window[0] + WWidth / 2 WYCenter = Window[1] + WHeight / 2 WXmin = WXCenter - (WWidth * zoom) WYmin = WYCenter - (WHeight * zoom) WXmax = WXCenter + (WWidth * zoom) WYmax = WYCenter + (WHeight * zoom) Visum.Graphic.SetWindow(WXmin, WYmin, WXmax, WYmax) Visum.Graphic.Screenshot(Paths["Screenshot"]) Screenshot = QtGui.QPixmap(Paths["Screenshot"]) Screenshot.scaled(350, 350, 0, 1) self.L_ImageLeft.setPixmap(Screenshot) except: self.L_GeoPos.setText("node does not exist") def closeEvent(self): os.remove(Paths["Screenshot"]) QtGui.qApp.quit() def openHelp(self): os.startfile(Paths["Help"])
class Widget(QWidget): def __init__(self, dockwidget): super(Widget, self).__init__(dockwidget) self._document = None self._midiin = midiinput.MidiIn(self) self._dockwidget = weakref.ref(dockwidget) signals = list() self._labelmidichannel = QLabel() self._midichannel = QComboBox() signals.append(self._midichannel.currentIndexChanged) self._labelkeysignature = QLabel() self._keysignature = QComboBox() signals.append(self._keysignature.currentIndexChanged) self._labelaccidentals = QLabel() self._accidentalssharps = QRadioButton() signals.append(self._accidentalssharps.clicked) self._accidentalsflats = QRadioButton() signals.append(self._accidentalsflats.clicked) self._groupaccidentals = QGroupBox() self._groupaccidentals.setFlat(True) hbox = QHBoxLayout() self._groupaccidentals.setLayout(hbox) hbox.addWidget(self._accidentalssharps) hbox.addWidget(self._accidentalsflats) self._accidentalssharps.setChecked(True) self._chordmode = QCheckBox() signals.append(self._chordmode.clicked) self._relativemode = QCheckBox() signals.append(self._relativemode.clicked) self._labeldamper = QLabel() self._damper = QComboBox() self._labelsostenuto = QLabel() self._sostenuto = QComboBox() self._labelsoft = QLabel() self._soft = QComboBox() ac = self.parentWidget().actionCollection self._capture = QToolButton() self._capture.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) self._capture.setDefaultAction(ac.capture_start) self._notemode = QLabel() layout = QVBoxLayout() self.setLayout(layout) grid = QGridLayout(spacing=0) layout.addLayout(grid) grid.addWidget(self._labelmidichannel, 0, 0) grid.addWidget(self._midichannel, 0, 1) grid.addWidget(self._labelkeysignature, 1, 0) grid.addWidget(self._keysignature, 1, 1) grid.addWidget(self._labelaccidentals, 2, 0) grid.addWidget(self._groupaccidentals, 2, 1) grid.addWidget(self._chordmode, 3, 0) grid.addWidget(self._relativemode, 3, 1) grid.addWidget(self._labeldamper, 4, 0) grid.addWidget(self._damper, 4, 1) grid.addWidget(self._labelsostenuto, 5, 0) grid.addWidget(self._sostenuto, 5, 1) grid.addWidget(self._labelsoft, 6, 0) grid.addWidget(self._soft, 6, 1) hbox = QHBoxLayout() layout.addLayout(hbox) hbox.addWidget(self._capture) hbox.addStretch() app.translateUI(self) self.loadsettings() for s in signals: s.connect(self.savesettings) def mainwindow(self): return self._dockwidget().mainwindow() def channel(self): return self._midichannel.currentIndex() def keysignature(self): return self._keysignature.currentIndex() def accidentals(self): if self._accidentalsflats.isChecked(): return 'flats' else: return 'sharps' def chordmode(self): return self._chordmode.isChecked() def relativemode(self): return self._relativemode.isChecked() def startcapturing(self): self._midiin.capture() ac = self.parentWidget().actionCollection while self._capture.actions(): # remove all old actions self._capture.removeAction(self._capture.actions()[0]) self._capture.setDefaultAction(ac.capture_stop) def stopcapturing(self): self._midiin.capturestop() ac = self.parentWidget().actionCollection while self._capture.actions(): # remove all old actions self._capture.removeAction(self._capture.actions()[0]) self._capture.setDefaultAction(ac.capture_start) def savesettings(self): s = QSettings() s.beginGroup("midiinputdock") s.setValue("midichannel", self._midichannel.currentIndex()) s.setValue("keysignature", self._keysignature.currentIndex()) if self._accidentalsflats.isChecked(): s.setValue("accidentals", 'flats') else: s.setValue("accidentals", 'sharps') s.setValue("chordmode", self._chordmode.isChecked()) s.setValue("relativemode", self._relativemode.isChecked()) def loadsettings(self): s = QSettings() s.beginGroup("midiinputdock") self._midichannel.setCurrentIndex(s.value("midichannel", 0, int)) self._keysignature.setCurrentIndex(s.value("keysignature", 7, int)) if s.value("accidentals", 'sharps', str) == 'flats': self._accidentalsflats.setChecked(True) else: self._accidentalssharps.setChecked(True) self._chordmode.setChecked(s.value("chordmode", False, bool)) self._relativemode.setChecked(s.value("relativemode", False, bool)) def translateUI(self): self._labelmidichannel.setText(_("MIDI channel")) self._midichannel.addItems([_("all")] + [str(i) for i in range(1, 17)]) self._labelkeysignature.setText(_("Key signature")) self._keysignature.addItems([ _("C flat major (7 flats)"), _("G flat major (6 flats)"), _("D flat major (5 flats)"), _("A flat major (4 flats)"), _("E flat major (3 flats)"), _("B flat major (2 flats)"), _("F major (1 flat)"), _("C major"), _("G major (1 sharp)"), _("D major (2 sharps)"), _("A major (3 sharps)"), _("E major (4 sharps)"), _("B major (5 sharps)"), _("F sharp major (6 sharps)"), _("C sharp major (7 sharps)") ]) self._keysignature.setCurrentIndex(7) self._labelaccidentals.setText(_("Accidentals")) self._accidentalssharps.setText(_("sharps")) self._accidentalsflats.setText(_("flats")) self._chordmode.setText(_("Chord mode")) self._chordmode.setToolTip( _("Enter simultaneously played notes as chords. " "See \"What's This\" for more information.")) self._chordmode.setWhatsThis( _("Notes which are played simultaneously are written " "as chords. As a consequence they are not written " "before the last key is lifted. Of course single " "can also be entered.")) self._relativemode.setText(_("Relative mode")) self._relativemode.setToolTip( _("Enter octaves of notes relative to the last note. " "See \"What's This\" for more information.")) self._relativemode.setWhatsThis( _("Enter octaves of notes relative to the last note. " "This refers to the last key pressed on the MIDI keyboard, not the last note in the document." "Hold Shift with a note to enter an octave check.")) self._labeldamper.setText(_("Damper pedal")) self._labelsostenuto.setText(_("Sostenuto pedal")) self._labelsoft.setText(_("Soft pedal"))
class PsychomotoCaDialog(QDialog): pagetitle = 'Skill-Assessment' holdc = {} hold = [] def __init__(self, parent=None): super(PsychomotoCaDialog, self).__init__(parent) ko = 0 self.subjects = self.pullSubjects() self.frame1 = QGroupBox('Skills') self.frame2 = QGroupBox('Categories') hc1_box = QVBoxLayout() hc2_box = QVBoxLayout() self.li = [] self.liID = [] for subject in self.subjects: num = subject['id'] self.liID.append(num) self.c = QRadioButton('cb' + str(num)) self.c.setText(str(subject['name']).upper()) self.c.setObjectName("chk" + str(num)) self.c.setChecked(False) self.c.toggled.connect( lambda state, x=num, y=self.c: self.catItems(x, y)) hc1_box.addWidget(self.c) self.li.append(self.c) ko += 1 self.li1 = [] self.li1ID = [] self.hc2_box = QVBoxLayout() self.frame1.setLayout(hc1_box) #frame1.setFrameShape(QFrame.StyledPanel) self.frame2.setLayout(self.hc2_box) #frame2.setFrameShape(QFrame.StyledPanel) h_box = QHBoxLayout() h_box.addWidget(self.frame1) h_box.addWidget(self.frame2) self.pb = QPushButton() self.pb.setObjectName("MakeEntries") self.pb.setText("Edit View") self.pb1 = QPushButton() self.pb1.setObjectName("View Report") self.pb1.setText("Report View") self.pb2 = QPushButton() self.pb2.setObjectName("Cancel") self.pb2.setText("Cancel") but_box = QHBoxLayout() but_box.addWidget(self.pb2) but_box.addWidget(self.pb1) but_box.addWidget(self.pb) main_box = QVBoxLayout() main_box.addLayout(h_box) main_box.addLayout(but_box) self.setLayout(main_box) self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click()) self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click()) self.connect(self.pb2, SIGNAL("clicked()"), lambda: self.button_close()) self.setWindowTitle(self.pagetitle) def catItems(self, a, b): _a = a self.cas = self.pullCas(_a) print(self.hold) self.li1 = [] self.li1ID = [] for rp in self.hold: self.hc2_box.removeWidget(rp) sip.delete(rp) self.hold = [] ko = 0 for ca in self.cas: num = ca['id'] self.li1ID.append(num) self.c1 = QCheckBox('cbx' + str(num)) self.c1.setText(str(ca['name']).upper()) self.c1.setObjectName("chkx" + str(num)) self.c1.setChecked(True) self.hc2_box.addWidget(self.c1) self.hold.append(self.c1) self.li1.append(self.c1) ko += 1 #self.hc2_box.show() def pullSubjects(self): cn = Db() arr = cn.selectn('datas', '', '', {'pubID': 9}) return arr def pullCas(self, a): _a = a cn = Db() arr = cn.selectn('datas', '', '', {'subID': _a}) return arr def button_close(self): self.reject() def button_click(self): self.accept() def getValue(self): k1 = [] k2 = [] for s in range(0, len(self.li)): if self.li[s].isChecked(): k1.append(self.liID[s]) else: k2.append(self.liID[s]) k11 = [] k21 = [] for s in range(0, len(self.li1)): if self.li1[s].isChecked(): k11.append(self.li1ID[s]) else: k21.append(self.li1ID[s]) return [k1, k11]
class RunDialog( QDialog ): """ Run parameters dialog implementation """ # See utils.run for runParameters def __init__( self, path, runParameters, termType, profilerParams, debuggerParams, action = "", parent = None ): QDialog.__init__( self, parent ) # Used as a return value self.termType = termType self.profilerParams = copy.deepcopy( profilerParams ) self.debuggerParams = copy.deepcopy( debuggerParams ) self.__action = action.lower() # Avoid pylint complains self.__argsEdit = None self.__scriptWDRButton = None self.__dirRButton = None self.__dirEdit = None self.__dirSelectButton = None self.__inheritParentRButton = None self.__inheritParentPlusRButton = None self.__inhPlusEnvTable = None self.__addInhButton = None self.__delInhButton = None self.__editInhButton = None self.__specificRButton = None self.__specEnvTable = None self.__addSpecButton = None self.__delSpecButton = None self.__editSpecButton = None self.__runButton = None self.__nodeLimitEdit = None self.__edgeLimitEdit = None self.__createLayout( action ) self.setWindowTitle( action + " parameters for " + path ) # Restore the values self.runParams = copy.deepcopy( runParameters ) self.__argsEdit.setText( self.runParams.arguments ) # Working dir if self.runParams.useScriptLocation: self.__scriptWDRButton.setChecked( True ) self.__dirEdit.setEnabled( False ) self.__dirSelectButton.setEnabled( False ) else: self.__dirRButton.setChecked( True ) self.__dirEdit.setEnabled( True ) self.__dirSelectButton.setEnabled( True ) self.__dirEdit.setText( self.runParams.specificDir ) # Environment self.__populateTable( self.__inhPlusEnvTable, self.runParams.additionToParentEnv ) self.__populateTable( self.__specEnvTable, self.runParams.specificEnv ) if self.runParams.envType == RunParameters.InheritParentEnv: self.__inheritParentRButton.setChecked( True ) self.__setEnabledInheritedPlusEnv( False ) self.__setEnabledSpecificEnv( False ) elif self.runParams.envType == RunParameters.InheritParentEnvPlus: self.__inheritParentPlusRButton.setChecked( True ) self.__setEnabledSpecificEnv( False ) else: self.__specificRButton.setChecked( True ) self.__setEnabledInheritedPlusEnv( False ) # Terminal if self.termType == TERM_REDIRECT: self.__redirectRButton.setChecked( True ) elif self.termType == TERM_AUTO: self.__autoRButton.setChecked( True ) elif self.termType == TERM_KONSOLE: self.__konsoleRButton.setChecked( True ) elif self.termType == TERM_GNOME: self.__gnomeRButton.setChecked( True ) else: self.__xtermRButton.setChecked( True ) # Close checkbox self.__closeCheckBox.setChecked( self.runParams.closeTerminal ) if self.termType == TERM_REDIRECT: self.__closeCheckBox.setEnabled( False ) # Profile limits if so if self.__action == "profile": if self.profilerParams.nodeLimit < 0.0 or \ self.profilerParams.nodeLimit > 100.0: self.profilerParams.nodeLimit = 1.0 self.__nodeLimitEdit.setText( str( self.profilerParams.nodeLimit ) ) if self.profilerParams.edgeLimit < 0.0 or \ self.profilerParams.edgeLimit > 100.0: self.profilerParams.edgeLimit = 1.0 self.__edgeLimitEdit.setText( str( self.profilerParams.edgeLimit ) ) elif self.__action == "debug": self.__reportExceptionCheckBox.setChecked( self.debuggerParams.reportExceptions ) self.__traceInterpreterCheckBox.setChecked( self.debuggerParams.traceInterpreter ) self.__stopAtFirstCheckBox.setChecked( self.debuggerParams.stopAtFirstLine ) self.__autoforkCheckBox.setChecked( self.debuggerParams.autofork ) self.__debugChildCheckBox.setChecked( self.debuggerParams.followChild ) self.__debugChildCheckBox.setEnabled( self.debuggerParams.autofork ) self.__setRunButtonProps() return @staticmethod def __populateTable( table, dictionary ): " Populates the given table " for key, value in dictionary.iteritems(): item = QTreeWidgetItem( [ key, value ] ) table.addTopLevelItem( item ) if dictionary: table.setCurrentItem( table.topLevelItem( 0 ) ) return def __setEnabledInheritedPlusEnv( self, value ): " Disables/enables 'inherited and add' section controls " self.__inhPlusEnvTable.setEnabled( value ) self.__addInhButton.setEnabled( value ) self.__delInhButton.setEnabled( value ) self.__editInhButton.setEnabled( value ) return def __setEnabledSpecificEnv( self, value ): " Disables/enables 'specific env' section controls " self.__specEnvTable.setEnabled( value ) self.__addSpecButton.setEnabled( value ) self.__delSpecButton.setEnabled( value ) self.__editSpecButton.setEnabled( value ) return def __createLayout( self, action ): """ Creates the dialog layout """ self.resize( 650, 300 ) self.setSizeGripEnabled( True ) # Top level layout layout = QVBoxLayout( self ) # Cmd line arguments argsLabel = QLabel( "Command line arguments" ) self.__argsEdit = QLineEdit() self.__argsEdit.textChanged.connect( self.__argsChanged ) argsLayout = QHBoxLayout() argsLayout.addWidget( argsLabel ) argsLayout.addWidget( self.__argsEdit ) layout.addLayout( argsLayout ) # Working directory workDirGroupbox = QGroupBox( self ) workDirGroupbox.setTitle( "Working directory" ) sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred ) sizePolicy.setHorizontalStretch( 0 ) sizePolicy.setVerticalStretch( 0 ) sizePolicy.setHeightForWidth( \ workDirGroupbox.sizePolicy().hasHeightForWidth() ) workDirGroupbox.setSizePolicy( sizePolicy ) gridLayoutWD = QGridLayout( workDirGroupbox ) self.__scriptWDRButton = QRadioButton( workDirGroupbox ) self.__scriptWDRButton.setText( "&Use script location" ) gridLayoutWD.addWidget( self.__scriptWDRButton, 0, 0 ) self.__scriptWDRButton.clicked.connect( self.__scriptWDirClicked ) self.__dirRButton = QRadioButton( workDirGroupbox ) self.__dirRButton.setText( "Select &directory" ) gridLayoutWD.addWidget( self.__dirRButton, 1, 0 ) self.__dirRButton.clicked.connect( self.__dirClicked ) self.__dirEdit = QLineEdit( workDirGroupbox ) gridLayoutWD.addWidget( self.__dirEdit, 1, 1 ) self.__dirEdit.textChanged.connect( self.__workingDirChanged ) self.__dirSelectButton = QPushButton( workDirGroupbox ) self.__dirSelectButton.setText( "..." ) gridLayoutWD.addWidget( self.__dirSelectButton, 1, 2 ) self.__dirSelectButton.clicked.connect( self.__selectDirClicked ) layout.addWidget( workDirGroupbox ) # Environment envGroupbox = QGroupBox( self ) envGroupbox.setTitle( "Environment" ) sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred ) sizePolicy.setHorizontalStretch( 0 ) sizePolicy.setVerticalStretch( 0 ) sizePolicy.setHeightForWidth( \ envGroupbox.sizePolicy().hasHeightForWidth() ) envGroupbox.setSizePolicy( sizePolicy ) layoutEnv = QVBoxLayout( envGroupbox ) self.__inheritParentRButton = QRadioButton( envGroupbox ) self.__inheritParentRButton.setText( "Inherit &parent" ) self.__inheritParentRButton.clicked.connect( self.__inhClicked ) layoutEnv.addWidget( self.__inheritParentRButton ) self.__inheritParentPlusRButton = QRadioButton( envGroupbox ) self.__inheritParentPlusRButton.setText( "Inherit parent and add/&modify" ) self.__inheritParentPlusRButton.clicked.connect( self.__inhPlusClicked ) layoutEnv.addWidget( self.__inheritParentPlusRButton ) hInhPlusLayout = QHBoxLayout() self.__inhPlusEnvTable = QTreeWidget() self.__inhPlusEnvTable.itemActivated.connect( self.__inhPlusItemActivated ) self.__tuneTable( self.__inhPlusEnvTable ) hInhPlusLayout.addWidget( self.__inhPlusEnvTable ) vInhPlusLayout = QVBoxLayout() self.__addInhButton = QPushButton() self.__addInhButton.clicked.connect( self.__addInhClicked ) self.__addInhButton.setText( 'Add' ) vInhPlusLayout.addWidget( self.__addInhButton ) self.__delInhButton = QPushButton() self.__delInhButton.clicked.connect( self.__delInhClicked ) self.__delInhButton.setText( 'Delete' ) vInhPlusLayout.addWidget( self.__delInhButton ) self.__editInhButton = QPushButton() self.__editInhButton.clicked.connect( self.__editInhClicked ) self.__editInhButton.setText( "Edit" ) vInhPlusLayout.addWidget( self.__editInhButton ) hInhPlusLayout.addLayout( vInhPlusLayout ) layoutEnv.addLayout( hInhPlusLayout ) self.__specificRButton = QRadioButton( envGroupbox ) self.__specificRButton.setText( "&Specific" ) self.__specificRButton.clicked.connect( self.__specClicked ) layoutEnv.addWidget( self.__specificRButton ) hSpecLayout = QHBoxLayout() self.__specEnvTable = QTreeWidget() self.__specEnvTable.itemActivated.connect( self.__specItemActivated ) self.__tuneTable( self.__specEnvTable ) hSpecLayout.addWidget( self.__specEnvTable ) vSpecLayout = QVBoxLayout() self.__addSpecButton = QPushButton() self.__addSpecButton.clicked.connect( self.__addSpecClicked ) self.__addSpecButton.setText( 'Add' ) vSpecLayout.addWidget( self.__addSpecButton ) self.__delSpecButton = QPushButton() self.__delSpecButton.clicked.connect( self.__delSpecClicked ) self.__delSpecButton.setText( 'Delete' ) vSpecLayout.addWidget( self.__delSpecButton ) self.__editSpecButton = QPushButton() self.__editSpecButton.clicked.connect( self.__editSpecClicked ) self.__editSpecButton.setText( "Edit" ) vSpecLayout.addWidget( self.__editSpecButton ) hSpecLayout.addLayout( vSpecLayout ) layoutEnv.addLayout( hSpecLayout ) layout.addWidget( envGroupbox ) # Terminal and profile limits if self.__action in [ "profile", "debug" ]: layout.addWidget( self.__getIDEWideGroupbox() ) else: termGroupbox = self.__getTermGroupbox() termGroupbox.setTitle( "Terminal to run in (IDE wide setting)" ) layout.addWidget( termGroupbox ) # Close checkbox self.__closeCheckBox = QCheckBox( "&Close terminal upon " "successful completion" ) self.__closeCheckBox.stateChanged.connect( self.__onCloseChanged ) layout.addWidget( self.__closeCheckBox ) # Buttons at the bottom buttonBox = QDialogButtonBox( self ) buttonBox.setOrientation( Qt.Horizontal ) buttonBox.setStandardButtons( QDialogButtonBox.Cancel ) self.__runButton = buttonBox.addButton( action, QDialogButtonBox.AcceptRole ) self.__runButton.setDefault( True ) self.__runButton.clicked.connect( self.onAccept ) layout.addWidget( buttonBox ) buttonBox.rejected.connect( self.close ) return def __getTermGroupbox( self ): " Creates the term groupbox " termGroupbox = QGroupBox( self ) sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred ) sizePolicy.setHorizontalStretch( 0 ) sizePolicy.setVerticalStretch( 0 ) sizePolicy.setHeightForWidth( termGroupbox.sizePolicy().hasHeightForWidth() ) termGroupbox.setSizePolicy( sizePolicy ) layoutTerm = QVBoxLayout( termGroupbox ) self.__redirectRButton = QRadioButton( termGroupbox ) self.__redirectRButton.setText( "&Redirect to IDE" ) self.__redirectRButton.toggled.connect( self.__redirectedChanged ) layoutTerm.addWidget( self.__redirectRButton ) self.__autoRButton = QRadioButton( termGroupbox ) self.__autoRButton.setText( "Aut&o detection" ) layoutTerm.addWidget( self.__autoRButton ) self.__konsoleRButton = QRadioButton( termGroupbox ) self.__konsoleRButton.setText( "Default &KDE konsole" ) layoutTerm.addWidget( self.__konsoleRButton ) self.__gnomeRButton = QRadioButton( termGroupbox ) self.__gnomeRButton.setText( "gnome-&terminal" ) layoutTerm.addWidget( self.__gnomeRButton ) self.__xtermRButton = QRadioButton( termGroupbox ) self.__xtermRButton.setText( "&xterm" ) layoutTerm.addWidget( self.__xtermRButton ) return termGroupbox def __redirectedChanged( self, checked ): " Triggered when the redirected radio button changes its state " self.__closeCheckBox.setEnabled( not checked ) return def __getIDEWideGroupbox( self ): " Creates the IDE wide groupbox " ideGroupbox = QGroupBox( self ) ideGroupbox.setTitle( "IDE Wide Settings" ) sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred ) sizePolicy.setHorizontalStretch( 0 ) sizePolicy.setVerticalStretch( 0 ) sizePolicy.setHeightForWidth( ideGroupbox.sizePolicy().hasHeightForWidth() ) ideGroupbox.setSizePolicy( sizePolicy ) layoutIDE = QHBoxLayout( ideGroupbox ) termGroupbox = self.__getTermGroupbox() termGroupbox.setTitle( "Terminal to run in" ) layoutIDE.addWidget( termGroupbox ) if self.__action == "profile": # Profile version of the dialog limitsGroupbox = self.__getProfileLimitsGroupbox() layoutIDE.addWidget( limitsGroupbox ) else: # Debug version of the dialog dbgGroupbox = self.__getDebugGroupbox() layoutIDE.addWidget( dbgGroupbox ) return ideGroupbox def __getProfileLimitsGroupbox( self ): " Creates the profile limits groupbox " limitsGroupbox = QGroupBox( self ) limitsGroupbox.setTitle( "Profiler diagram limits" ) sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred ) sizePolicy.setHorizontalStretch( 0 ) sizePolicy.setVerticalStretch( 0 ) sizePolicy.setHeightForWidth( limitsGroupbox.sizePolicy().hasHeightForWidth() ) limitsGroupbox.setSizePolicy( sizePolicy ) layoutLimits = QGridLayout( limitsGroupbox ) self.__nodeLimitEdit = QLineEdit() self.__nodeLimitEdit.textEdited.connect( self.__setRunButtonProps ) self.__nodeLimitValidator = QDoubleValidator( 0.0, 100.0, 2, self ) self.__nodeLimitValidator.setNotation( QDoubleValidator.StandardNotation ) self.__nodeLimitEdit.setValidator( self.__nodeLimitValidator ) nodeLimitLabel = QLabel( "Hide nodes below" ) self.__edgeLimitEdit = QLineEdit() self.__edgeLimitEdit.textEdited.connect( self.__setRunButtonProps ) self.__edgeLimitValidator = QDoubleValidator( 0.0, 100.0, 2, self ) self.__edgeLimitValidator.setNotation( QDoubleValidator.StandardNotation ) self.__edgeLimitEdit.setValidator( self.__edgeLimitValidator ) edgeLimitLabel = QLabel( "Hide edges below" ) layoutLimits.addWidget( nodeLimitLabel, 0, 0 ) layoutLimits.addWidget( self.__nodeLimitEdit, 0, 1 ) layoutLimits.addWidget( QLabel( "%" ), 0, 2 ) layoutLimits.addWidget( edgeLimitLabel, 1, 0 ) layoutLimits.addWidget( self.__edgeLimitEdit, 1, 1 ) layoutLimits.addWidget( QLabel( "%" ), 1, 2 ) return limitsGroupbox def __getDebugGroupbox( self ): " Creates the debug settings groupbox " dbgGroupbox = QGroupBox( self ) dbgGroupbox.setTitle( "Debugger" ) sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred ) sizePolicy.setHorizontalStretch( 0 ) sizePolicy.setVerticalStretch( 0 ) sizePolicy.setHeightForWidth( dbgGroupbox.sizePolicy().hasHeightForWidth() ) dbgGroupbox.setSizePolicy( sizePolicy ) dbgLayout = QVBoxLayout( dbgGroupbox ) self.__reportExceptionCheckBox = QCheckBox( "Report &exceptions" ) self.__reportExceptionCheckBox.stateChanged.connect( self.__onReportExceptionChanged ) self.__traceInterpreterCheckBox = QCheckBox( "T&race interpreter libs" ) self.__traceInterpreterCheckBox.stateChanged.connect( self.__onTraceInterpreterChanged ) self.__stopAtFirstCheckBox = QCheckBox( "Stop at first &line" ) self.__stopAtFirstCheckBox.stateChanged.connect( self.__onStopAtFirstChanged ) self.__autoforkCheckBox = QCheckBox( "&Fork without asking" ) self.__autoforkCheckBox.stateChanged.connect(self.__onAutoforkChanged ) self.__debugChildCheckBox = QCheckBox( "Debu&g child process" ) self.__debugChildCheckBox.stateChanged.connect( self.__onDebugChild ) dbgLayout.addWidget( self.__reportExceptionCheckBox ) dbgLayout.addWidget( self.__traceInterpreterCheckBox ) dbgLayout.addWidget( self.__stopAtFirstCheckBox ) dbgLayout.addWidget( self.__autoforkCheckBox ) dbgLayout.addWidget( self.__debugChildCheckBox ) return dbgGroupbox @staticmethod def __tuneTable( table ): " Sets the common settings for a table " table.setAlternatingRowColors( True ) table.setRootIsDecorated( False ) table.setItemsExpandable( False ) table.setUniformRowHeights( True ) table.setSelectionMode( QAbstractItemView.SingleSelection ) table.setSelectionBehavior( QAbstractItemView.SelectRows ) table.setItemDelegate( NoOutlineHeightDelegate( 4 ) ) table.setHeaderLabels( [ "Variable", "Value" ] ) header = table.header() header.setSortIndicator( 0, Qt.AscendingOrder ) header.setSortIndicatorShown( True ) header.setClickable( True ) table.setSortingEnabled( True ) return def __scriptWDirClicked( self ): " The script working dir button is clicked " self.__dirEdit.setEnabled( False ) self.__dirSelectButton.setEnabled( False ) self.runParams.useScriptLocation = True self.__setRunButtonProps() return def __dirClicked( self ): " The script specific working dir button is clicked " self.__dirEdit.setEnabled( True ) self.__dirSelectButton.setEnabled( True ) self.runParams.useScriptLocation = False self.__setRunButtonProps() return def __argsChanged( self, value ): " Triggered when cmd line args are changed " value = str( value ).strip() self.runParams.arguments = value self.__setRunButtonProps() return def __workingDirChanged( self, value ): " Triggered when a working dir value is changed " value = str( value ) self.runParams.specificDir = value self.__setRunButtonProps() return def __onCloseChanged( self, state ): " Triggered when the close terminal check box changed " self.runParams.closeTerminal = state != 0 return def __onReportExceptionChanged( self, state ): " Triggered when exception report check box changed " self.debuggerParams.reportExceptions = state != 0 return def __onTraceInterpreterChanged( self, state ): " Triggered when trace interpreter changed " self.debuggerParams.traceInterpreter = state != 0 return def __onStopAtFirstChanged( self, state ): " Triggered when stop at first changed " self.debuggerParams.stopAtFirstLine = state != 0 return def __onAutoforkChanged( self, state ): " Triggered when autofork changed " self.debuggerParams.autofork = state != 0 self.__debugChildCheckBox.setEnabled( self.debuggerParams.autofork ) return def __onDebugChild( self, state ): " Triggered when debug child changed " self.debuggerParams.followChild = state != 0 return def __argumentsOK( self ): " Returns True if the arguments are OK " try: parseCommandLineArguments( self.runParams.arguments ) return True except: return False def __dirOK( self ): " Returns True if the working dir is OK " if self.__scriptWDRButton.isChecked(): return True return os.path.isdir( self.__dirEdit.text() ) def __setRunButtonProps( self, newText = None ): " Enable/disable run button and set its tooltip " if not self.__argumentsOK(): self.__runButton.setEnabled( False ) self.__runButton.setToolTip( "No closing quotation in arguments" ) return if not self.__dirOK(): self.__runButton.setEnabled( False ) self.__runButton.setToolTip( "The given working " "dir is not found" ) return if self.__nodeLimitEdit is not None: txt = self.__nodeLimitEdit.text().strip() try: value = float( txt ) if value < 0.0 or value > 100.0: raise Exception( "Out of range" ) except: self.__runButton.setEnabled( False ) self.__runButton.setToolTip( "The given node limit " "is out of range" ) return if self.__edgeLimitEdit is not None: txt = self.__edgeLimitEdit.text().strip() try: value = float( txt ) if value < 0.0 or value > 100.0: raise Exception( "Out of range" ) except: self.__runButton.setEnabled( False ) self.__runButton.setToolTip( "The given edge limit " "is out of range" ) return self.__runButton.setEnabled( True ) self.__runButton.setToolTip( "Save parameters and " + self.__action + " script" ) return def __selectDirClicked( self ): " Selects the script working dir " dirName = QFileDialog.getExistingDirectory( self, "Select the script working directory", self.__dirEdit.text(), QFileDialog.Options( QFileDialog.ShowDirsOnly ) ) if dirName: self.__dirEdit.setText( os.path.normpath( dirName ) ) return def __inhClicked( self ): " Inerit parent env radio button clicked " self.__setEnabledInheritedPlusEnv( False ) self.__setEnabledSpecificEnv( False ) self.runParams.envType = RunParameters.InheritParentEnv return def __inhPlusClicked( self ): " Inherit parent and add radio button clicked " self.__setEnabledInheritedPlusEnv( True ) self.__setEnabledSpecificEnv( False ) self.runParams.envType = RunParameters.InheritParentEnvPlus if self.__inhPlusEnvTable.selectedIndexes(): self.__delInhButton.setEnabled( True ) self.__editInhButton.setEnabled( True ) else: self.__delInhButton.setEnabled( False ) self.__editInhButton.setEnabled( False ) return def __specClicked( self ): " Specific env radio button clicked " self.__setEnabledInheritedPlusEnv( False ) self.__setEnabledSpecificEnv( True ) self.runParams.envType = RunParameters.SpecificEnvironment if self.__specEnvTable.selectedIndexes(): self.__delSpecButton.setEnabled( True ) self.__editSpecButton.setEnabled( True ) else: self.__delSpecButton.setEnabled( False ) self.__editSpecButton.setEnabled( False ) return @staticmethod def __delAndInsert( table, name, value ): " Deletes an item by name if so; insert new; highlight it " for index in xrange( table.topLevelItemCount() ): item = table.topLevelItem( index ) if str( item.text( 0 ) ) == name: table.takeTopLevelItem( index ) break item = QTreeWidgetItem( [ name, value ] ) table.addTopLevelItem( item ) table.setCurrentItem( item ) return item def __addInhClicked( self ): " Add env var button clicked " dlg = EnvVarDialog() if dlg.exec_() == QDialog.Accepted: name = str( dlg.name ) value = str( dlg.value ) self.__delAndInsert( self.__inhPlusEnvTable, name, value ) self.runParams.additionToParentEnv[ name ] = value self.__delInhButton.setEnabled( True ) self.__editInhButton.setEnabled( True ) return def __addSpecClicked( self ): " Add env var button clicked " dlg = EnvVarDialog() if dlg.exec_() == QDialog.Accepted: name = str( dlg.name ) value = str( dlg.value ) self.__delAndInsert( self.__specEnvTable, name, value ) self.runParams.specificEnv[ name ] = value self.__delSpecButton.setEnabled( True ) self.__editSpecButton.setEnabled( True ) return def __delInhClicked( self ): " Delete the highlighted variable " if self.__inhPlusEnvTable.topLevelItemCount() == 0: return name = self.__inhPlusEnvTable.currentItem().text( 0 ) for index in xrange( self.__inhPlusEnvTable.topLevelItemCount() ): item = self.__inhPlusEnvTable.topLevelItem( index ) if name == item.text( 0 ): self.__inhPlusEnvTable.takeTopLevelItem( index ) break del self.runParams.additionToParentEnv[ str( name ) ] if self.__inhPlusEnvTable.topLevelItemCount() == 0: self.__delInhButton.setEnabled( False ) self.__editInhButton.setEnabled( False ) else: self.__inhPlusEnvTable.setCurrentItem( \ self.__inhPlusEnvTable.topLevelItem( 0 ) ) return def __delSpecClicked( self ): " Delete the highlighted variable " if self.__specEnvTable.topLevelItemCount() == 0: return name = self.__specEnvTable.currentItem().text( 0 ) for index in xrange( self.__specEnvTable.topLevelItemCount() ): item = self.__specEnvTable.topLevelItem( index ) if name == item.text( 0 ): self.__specEnvTable.takeTopLevelItem( index ) break del self.runParams.specificEnv[ str( name ) ] if self.__specEnvTable.topLevelItemCount() == 0: self.__delSpecButton.setEnabled( False ) self.__editSpecButton.setEnabled( False ) else: self.__specEnvTable.setCurrentItem( \ self.__specEnvTable.topLevelItem( 0 ) ) return def __editInhClicked( self ): " Edits the highlighted variable " if self.__inhPlusEnvTable.topLevelItemCount() == 0: return item = self.__inhPlusEnvTable.currentItem() dlg = EnvVarDialog( str( item.text( 0 ) ), str( item.text( 1 ) ), self ) if dlg.exec_() == QDialog.Accepted: name = str( dlg.name ) value = str( dlg.value ) self.__delAndInsert( self.__inhPlusEnvTable, name, value ) self.runParams.additionToParentEnv[ name ] = value return def __inhPlusItemActivated( self, item, column ): " Triggered when a table item is activated " self.__editInhClicked() return def __editSpecClicked( self ): " Edits the highlighted variable " if self.__specEnvTable.topLevelItemCount() == 0: return item = self.__specEnvTable.currentItem() dlg = EnvVarDialog( str( item.text( 0 ) ), str( item.text( 1 ) ), self ) if dlg.exec_() == QDialog.Accepted: name = str( dlg.name ) value = str( dlg.value ) self.__delAndInsert( self.__specEnvTable, name, value ) self.runParams.specificEnv[ name ] = value return def __specItemActivated( self, item, column ): " Triggered when a table item is activated " self.__editSpecClicked() return def onAccept( self ): " Saves the selected terminal and profiling values " if self.__redirectRButton.isChecked(): self.termType = TERM_REDIRECT elif self.__autoRButton.isChecked(): self.termType = TERM_AUTO elif self.__konsoleRButton.isChecked(): self.termType = TERM_KONSOLE elif self.__gnomeRButton.isChecked(): self.termType = TERM_GNOME else: self.termType = TERM_XTERM if self.__action == "profile": self.profilerParams.nodeLimit = float( self.__nodeLimitEdit.text() ) self.profilerParams.edgeLimit = float( self.__edgeLimitEdit.text() ) self.accept() return
class Mplayer(QDialog): REVENIR, PAS_PRECEDENT_SUIVANT, PRECEDENT_SUIVANT, CURSEUR_SUR_UNE_LIGNE,\ CURSEUR_A_PART, PARCOURIR, PAS_PARCOURIR, LIST, RATIO = range(9) HAUTEUR, LARGEUR = range(2) def __init__(self, cheminVideo=[], taille=(250,225), choixWidget=(RATIO, REVENIR, PAS_PRECEDENT_SUIVANT,CURSEUR_SUR_UNE_LIGNE,PAS_PARCOURIR,LIST), debutFin=(0,0), cheminMPlayer=None, barreTaches=None, facteurLimitant=HAUTEUR, cheminParcourir=None, parent=None): """widget mplayer""" QDialog.__init__(self, parent) #=== Paramètres généraux ===# self.setAttribute(Qt.WA_DeleteOnClose) self.setWindowTitle(_(u"Player vidéo")) #On réduit la marge pour gagner de l'espace self.setContentsMargins(0,0,0,0) self.systeme = os.name ### Quand EKD windows est installé, le chemin des dépendances sont ########### ### positionnées dans les variables d'environnement donc pas besoin de ####### ### collecter le chemin des ces dépendances ################################## self.cheminMPlayer = "mplayer" ############################################################################## # liste de chemins vidéos if type(cheminVideo) != list : self.listeVideos=[cheminVideo] else : self.listeVideos = cheminVideo # est-ce que la vidéo est lue? self.estLue=False # est-ce que la vidéo est en pause? self.estEnPause=False self.debutFin = debutFin # Nom du fichier courant (le self n'est pas encore utile) txtParDefaut = u"Pas de fichier lu" if self.listeVideos.__len__()!=0: self.fichierCourant = [txtParDefaut, self.listeVideos[0]] else: self.fichierCourant = [txtParDefaut, ""] # Barre des tâches de la fenêtre self.barreTaches = barreTaches # Taille de la vidéo self.tailleLargeur=taille[0] self.tailleHauteur=taille[1] # paramètres des boutons-icones iconTaille=22 flat=1 # Pour récupérer le temps courant depuis certains cadre self.temps = 0 self.dureeTimer = 10 # temps en ms ############################################################################################################################### #Pour être plus précis lors de la lecture, on prend comme unité la miliseconde. ###################### ## Il faut donc utiliser une echelle 1000 fois plus grande pour les unités du slider self.echelle=1000 ############################################################################################################################### # Permet de récupérer la durée de la vidéo depuis une instance de la classe # Sert dans certains cadres self.dureeVideo = 0 # Chemin sur lequel peut s'ouvrir la boite de dialogue de fichier # associée au bouton parcourir self.cheminPourBoutonParcourir = cheminParcourir self.taille = taille debug("self.taille avant lecture : %s %s" % (self.taille, type(self.taille))) #=== Widgets ===# self.icone_lire=QIcon("Icones" + os.sep + "player_play.png") self.icone_pause=QIcon("Icones" + os.sep + "player_pause.png") self.icone_arret=QIcon("Icones" + os.sep + "player_stop.png") if Mplayer.REVENIR in choixWidget: self.bout_revenir = QPushButton(u"Revenir") self.bout_revenir.setIcon(QIcon("Icones" + os.sep + "revenir.png")) if Mplayer.PARCOURIR in choixWidget: self.bout_ouvVideo = QPushButton(u"Parcourir...") if Mplayer.PRECEDENT_SUIVANT in choixWidget: self.bout_prec = QPushButton(QIcon("Icones" + os.sep + "player_rew.png"),"") self.bout_prec.setIconSize(QSize(iconTaille, iconTaille)) self.bout_prec.setFlat(flat) self.bout_suivant = QPushButton(QIcon("Icones" + os.sep + "player_fwd.png"),"") self.bout_suivant.setIconSize(QSize(iconTaille, iconTaille)) self.bout_suivant.setFlat(flat) self.LISTW=False if Mplayer.LIST in choixWidget : self.LISTW = True self.listFichiers = QComboBox() self.listFichiers.hide() self.setListeVideo() self.bout_LectPause = QPushButton(self.icone_lire,"") self.bout_LectPause.setIconSize(QSize(iconTaille, iconTaille)) self.bout_LectPause.setFlat(flat) self.bout_Arret = QPushButton(self.icone_arret,"") self.bout_Arret.setIconSize(QSize(iconTaille, iconTaille)) self.bout_Arret.setFlat(flat) # widget qui contiendra la vidéo self.cibleVideo = DisplayVid(self) # par défaut le widget-cible est noir color = QColor(0, 0, 0) self.cibleVideo.setAutoFillBackground(True) self.cibleVideo.setPalette(QPalette(color)) self.cibleVideo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.cibleVideo.setFixedHeight(self.taille[1]) self.cibleVideo.setToolTip(self.fichierCourant[0]) #Choix de l'aspect ratio de la vidéo if Mplayer.RATIO in choixWidget : self.conf = QGroupBox() self.conf.setContentsMargins(0,0,0,0) self.conf.setMinimumSize(QSize(self.tailleLargeur, 0)) self.conf.setObjectName("conf") self.verticalLayout = QHBoxLayout(self.conf) self.verticalLayout.setObjectName("verticalLayout") self.choicenorm = QRadioButton(self.conf) self.choicenorm.setObjectName("choicenorm") self.verticalLayout.addWidget(self.choicenorm) self.choicewide = QRadioButton(self.conf) self.choicewide.setObjectName("choicewide") self.verticalLayout.addWidget(self.choicewide) self.choiceone = QRadioButton(self.conf) self.choiceone.setObjectName("choiceone") self.verticalLayout.addWidget(self.choiceone) self.choicenorm.setText("4:3") self.choicewide.setText("16:9") self.choiceone.setText("w:h") # Checked le ratio de la vidéo if self.listeVideos.__len__()!=0: self.changeRatio(self.listeVideos[0]) else : self.setRatio(4.0/3.0) if Mplayer.RATIO in choixWidget : self.choicenorm.setChecked(True) self.slider = QSlider(Qt.Horizontal) self.slider.setEnabled(True) self.mplayerProcess = QProcess(self) self.timer = QTimer(self) self.tempsChrono = TracerChrono() #=== mise-en-page/plan ===# mhbox = QHBoxLayout() vbox = QVBoxLayout() vbox.addWidget(self.cibleVideo) if Mplayer.RATIO in choixWidget : vbox.addWidget(self.conf) hbox = QHBoxLayout() if Mplayer.REVENIR in choixWidget: hbox.addWidget(self.bout_revenir) if Mplayer.PARCOURIR in choixWidget: hbox.addWidget(self.bout_ouvVideo) hbox.addWidget(self.bout_LectPause) hbox.addWidget(self.bout_Arret) if Mplayer.PRECEDENT_SUIVANT in choixWidget: hbox.addWidget(self.bout_prec) hbox.addWidget(self.bout_suivant) hbox.addWidget(self.tempsChrono) if Mplayer.CURSEUR_A_PART not in choixWidget: hbox.addWidget(self.slider) vbox.addLayout(hbox) if Mplayer.CURSEUR_A_PART in choixWidget: hbox.setAlignment(Qt.AlignLeft) hbox = QHBoxLayout() hbox.addWidget(self.slider) vbox.addLayout(hbox) # Liste fichier dans combobox if self.LISTW : hbox = QHBoxLayout() hbox.addWidget(self.listFichiers) vbox.addLayout(hbox) mhbox.addLayout(vbox) self.setLayout(mhbox) #=== connexion des widgets à des fonctions ===# if Mplayer.REVENIR in choixWidget: self.connect(self.bout_revenir, SIGNAL('clicked()'), SLOT('close()')) if Mplayer.PARCOURIR in choixWidget: self.connect(self.bout_ouvVideo, SIGNAL('clicked()'), self.ouvrirVideo) if Mplayer.PRECEDENT_SUIVANT in choixWidget: self.connect(self.bout_prec, SIGNAL('clicked()'), self.precedent) self.connect(self.bout_suivant, SIGNAL('clicked()'), self.suivant) #Ajouté le 08/11/2009 - Liste des fichiers dans une combobox if self.LISTW : self.connect(self.listFichiers, SIGNAL('currentIndexChanged(int)'), self.changeVideo) self.connect(self.bout_LectPause, SIGNAL('clicked()'), self.lectPause) self.connect(self.bout_Arret, SIGNAL('clicked()'), self.arretMPlayer) self.connect(self.mplayerProcess, SIGNAL('readyReadStandardOutput()'), self.recupSortie) self.connect(self.mplayerProcess, SIGNAL('finished(int,QProcess::ExitStatus)'), self.finVideo) self.connect(self.timer, SIGNAL('timeout()'), self.sonderTempsActuel) self.connect(self.slider, SIGNAL('sliderMoved(int)'), self.changerTempsCurseur) self.connect(self.cibleVideo, SIGNAL('changeSize'), self.sizeMplayer) if Mplayer.RATIO in choixWidget : self.connect(self.choicenorm, SIGNAL("clicked(bool)"), self.defRatio) self.connect(self.choicewide, SIGNAL("clicked(bool)"), self.defRatio) self.connect(self.choiceone, SIGNAL("clicked(bool)"), self.defRatio) def setListeVideo(self) : self.referenceVideo = [] self.listFichiers.clear() for vid in self.listeVideos : self.referenceVideo.append(vid) self.listFichiers.addItem(os.path.basename(vid)) if self.listeVideos.__len__() > 1 : self.listFichiers.show() def setAudio(self,au) : if au : self.cibleVideo.hide() if "conf" in self.__dict__ : self.conf.hide() else : self.cibleVideo.show() if "conf" in self.__dict__ : self.conf.show() def changeVideo(self, index) : self.arretMPlayer() if index >= 0 : # Condition ajoutée pour éviter une erreure de dépassement de range dans la liste. self.listeVideos = self.referenceVideo[index] self.listFichiers.setCurrentIndex(index) def defRatio(self, state=0) : if state : if self.choicenorm.isChecked() : self.setRatio(4.0/3.0) if self.choicewide.isChecked() : self.setRatio(16.0/9.0) if self.choiceone.isChecked() : try : dim=getVideoSize(unicode(self.listeVideos[0])) self.setRatio(dim[0]/dim[1]) except : None self.defRatio() else : self.adjustSize() def setRatio(self,ratio) : self.ratio = ratio self.sizeMplayer() def changeRatio(self,video) : rv = getVideoRatio(video) if rv[0]==0.0 and type(rv[1])==float : rat = rv[1] else : rat = rv[0] if rat > 1.7 : if "choicewide" in self.__dict__ : self.choicewide.setChecked(True) self.setRatio(16.0/9.0) elif rat > 1.3 and rat <= 1.7 : if "choicenorm" in self.__dict__ : self.choicenorm.setChecked(True) self.setRatio(4.0/3.0) elif rat < 1.3 and rat != 0.0 : if "choiceone" in self.__dict__ : self.choiceone.setChecked(True) dim=getVideoSize(video) self.setRatio(dim[0]/dim[1]) else : if "choicenorm" in self.__dict__ : self.choicenorm.setChecked(True) self.setRatio(4.0/3.0) def sizeMplayer(self) : self.cibleVideo.setFixedHeight(int(self.cibleVideo.width()/self.ratio)) def ouvrirVideo(self): """Ouverture de la boîte de dialogue de fichiers""" txt = u"Fichiers vidéo" if self.cheminPourBoutonParcourir: chemin = self.cheminPourBoutonParcourir else: try: chemin = EkdConfig.get('general','video_input_path').decode("UTF8") except: chemin = os.path.expanduser('~') liste=QFileDialog.getOpenFileNames(None, u"Ouvrir", chemin, "%s (*.avi *.mpg *.mpeg *.mjpeg *.flv *.mp4 *.ogg *.vob *.mov *.wmv *.3gp *.h264)\n*" %txt) if not liste: return self.listeVideos = liste self.changeRatio(unicode(self.listeVideos[0])) chemin = unicode(self.listeVideos[0]) EkdConfig.set('general','video_input_path',os.path.dirname(chemin).encode("UTF8")) def setVideos(self, videos) : '''Définie proprement la liste des vidéos à jouer''' if type(videos) != list : self.listeVideos = [videos] else : self.listeVideos = videos if self.LISTW and videos.__len__() > 1 : self.setListeVideo() elif self.LISTW : self.listFichiers.hide() def demarrerMPlayer(self): """démarrage de mplayer avec les arguments choisis""" if self.estLue: return True args = QStringList() # Liste Qt qui contiendra les options de mplayer # Ajout d'options à liste: args << "-option" # mplayer fonctionnera comme un terminal dans ce script args << "-slave" # on ne veut pas avoir des commentaires sans grand intérêt args << "-quiet" # Sous linux, aucun driver n'a été nécessaire et pas de manip pour Wid :) if self.systeme=='posix': # try - except? # la fenêtre de mplayer restera attaché à la fenêtre # wid prend en valeur le nombre identifiant le widget (celui qui contiendra la vidéo) args << "-wid" << QString.number(self.cibleVideo.winId()) # Objet QString car args est une liste de ch de caractères settings = QSettings() videoOutput = settings.value("vo", QVariant('')).toString() if videoOutput: args << '-vo' << videoOutput # Sous windows else: # reinterpret_cast<qlonglong> obligatoire, winId() ne se laissant pas convertir gentiment ;) args << "-wid" << self.cibleVideo.winId().__hex__() args << "-vo" << "directx:noaccel" #args << "-vo" << "gl" # alternative # chemin de la vidéo args << self.listeVideos if PYQT_VERSION_STR >= "4.1.0": # mode de canal: on fusionne le canal de sortie normal (stdout) et celui des erreurs (stderr) self.mplayerProcess.setProcessChannelMode(QProcess.MergedChannels) # démarrage de mplayer (en tenant compte des arguments définis ci-dessus) # comme un nouveau processus self.mplayerProcess.start(self.cheminMPlayer, args) # au cas où mplayer ne démarrerait pas au bout de 3 sec (ex. problème de codec) if not self.mplayerProcess.waitForStarted(3000): QMessageBox.critical(self, u"Avertissement", u"Bogue au lancement de la vidéo avec mplayer") return False # donne le temps toutes les x secondes self.timer.start(self.dureeTimer) self.estLue = True return True def recupSortie(self): """récupère les lignes d'information émises par QProcess (mplayerProcess) et en tire les conséquences""" while self.mplayerProcess.canReadLine(): # renvoie True si une ligne complète peut être lue à partir du système # stocker l'ensemble des bits d'une ligne tampon=QByteArray(self.mplayerProcess.readLine()) # readline: lit une ligne ascii à partir du système # On vérifie si on a eu des réponses if tampon.startsWith("Playing"): # On récupère les infos de base ('$ mplayer -input cmdlist' pour avoir la liste complète - file:///usr/share/doc/mplayer-doc/tech/slave.txt.gz pour plus de détails) self.mplayerProcess.write("get_video_resolution\n") # récupère la résolution de la vidéo self.mplayerProcess.write("get_time_length\n") # Nouveau fichier chargé -> on récupère son nom ind = tampon.length() - 2 # suppression du '.' à la fin tampon.remove(ind,ind) tampon.remove(0, 8) # vire Playing tampon.replace(QByteArray("\n"), QByteArray("")) tampon.replace(QByteArray("\r"), QByteArray("")) try: # Tour de passe-passe pour ne pas avoir de problème d'accents # Condition pour détection windows if os.name == 'nt': self.fichierCourant[1]=unicode(QString(tampon)) # Condition pour détection Linux ou MacOSX elif os.name in ['posix', 'mac']: self.fichierCourant[1]=unicode(QString(tampon)).encode("Latin1").decode("UTF8") except UnicodeEncodeError, e: debug(e) self.fichierCourant[1]="?" self.cibleVideo.setToolTip(self.fichierCourant[1]) if self.barreTaches is not None: self.barreTaches.showMessage(self.fichierCourant[1]) # réponse à get_video_resolution : ANS_VIDEO_RESOLUTION='<width> x <height>' if tampon.startsWith("ANS_VIDEO_RESOLUTION"): # retourne True si l'ensemble de bits démarre avec "..." debug("tampon : %s" % tampon) # ex. -> ANS_VIDEO_RESOLUTION='352 x 288' tampon.remove(0, 21) # suppression des 21 1er caract -> '352 x 288' tampon.replace(QByteArray("'"), QByteArray("")) # -> 352 x 288 tampon.replace(QByteArray(" "), QByteArray("")) # -> 352x288 tampon.replace(QByteArray("\n"), QByteArray("")) # -> 352x288 # retour chariot unix tampon.replace(QByteArray("\r"), QByteArray("")) # -> 352x288 # retour chariot windows #print "-----tampon.indexOf('x') :", tampon.indexOf('x'), type(tampon.indexOf('x')) sepIndex = tampon.indexOf('x') # récupère la position de 'x' # 3 <type 'int'> #print "-----tampon.left(sepIndex).toInt():", tampon.left(sepIndex).toInt(), type(tampon.left(sepIndex).toInt()) resX = tampon.left(sepIndex).toInt()[0] # -> 352 # (352, True) <type 'tuple'> #print "-----tampon.mid(sepIndex+1).toInt() :", tampon.mid(sepIndex+1).toInt(), type(tampon.mid(sepIndex+1).toInt()) resY = tampon.mid(sepIndex+1).toInt()[0] # -> 288 # (288, True) <type 'tuple'> # on définit les nouvelles dimensions de l'image du widget-mplayer. # try pour éviter les bogues sur les fichiers audio (sans dimension d'image)!!! #try: if resX!=0 or resY!=0: debug( "ratio : %s - %s" % (self.ratio, type(self.ratio))) else: debug("fichier audio") # réponse à get_time_length : ANS_LENGTH=xx.yy elif tampon.startsWith("ANS_LENGTH"): debug("tampon : %s" % tampon) # -> ANS_LENGTH=279.38 tampon.remove(0, 11) # vire ANS_LENGTH= tampon.replace(QByteArray("'"), QByteArray("")) tampon.replace(QByteArray(" "), QByteArray("")) tampon.replace(QByteArray("\n"), QByteArray("")) tampon.replace(QByteArray("\r"), QByteArray("")) # -> 279.38 #print "-----tampon.toFloat() :", tampon.toFloat(), type(tampon.toFloat()) tempsMax = tampon.toFloat()[0] # (279.3800048828125, True) <type 'tuple'> self.dureeVideo = tempsMax ## Modifié le 28/05/2009 : On augmente la précision du slider #self.slider.setMaximum(tempsMax) # déf du domaine de valeur du curseur self.slider.setMaximum(tempsMax*self.echelle) # ATTENTION J'AI COMMENTE CETTE LIGNE !!! #self.slider.setMaximum(tempsMax) # réponse à get_time_pos : ANS_TIME_POSITION=xx.y elif tampon.startsWith("ANS_TIME_POSITION"): #print "tampon :",tampon # -> ANS_TIME_POSITION=1.4 (temps courant) tampon.remove(0, 18) # vire ANS_TIME_POSITION= tampon.replace(QByteArray("'"), QByteArray("")) tampon.replace(QByteArray(" "), QByteArray("")) tampon.replace(QByteArray("\n"), QByteArray("")) tampon.replace(QByteArray("\r"), QByteArray("")) #print "-----tampon.toFloat() :", tampon.toFloat(), type(tampon.toFloat()) tempsCourant = tampon.toFloat()[0] # (1.3999999761581421, True) <type 'tuple'> # récupération du temps courant: utile dans certains cadres self.temps = tempsCourant # Programmer un arrêt. Utile pour les aperçus temps = float("%.1f" %self.temps) if self.debutFin!=(0,0) and self.debutFin[1]==temps: self.arretMPlayer() return self.slider.setValue(tempsCourant*self.echelle) ############################################################################# self.changerTempsChrono(tempsCourant) # modifier le chrono du bouton
class DlgAixmInsertLeg(QDialog): def __init__(self, parent=None): QDialog.__init__(self, parent) self.resize(290, 136) self.setWindowTitle("Insert Leg") sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth()) self.setSizePolicy(sizePolicy) verticalLayoutDlg = QVBoxLayout(self) verticalLayoutDlg.setObjectName(("verticalLayoutDlg")) self.groupBox = GroupBox(self) verticalLayoutDlg.addWidget(self.groupBox) self.optBefore = QRadioButton(self.groupBox) self.optBefore.setObjectName("optBefore") self.optBefore.setText("Insert Before") self.groupBox.Add = self.optBefore self.optAfter = QRadioButton(self.groupBox) self.optAfter.setObjectName("optAfter") self.optAfter.setText("Insert After") self.groupBox.Add = self.optAfter self.optAppend = QRadioButton(self.groupBox) self.optAppend.setObjectName("optAppend") self.optAppend.setText("Append") self.groupBox.Add = self.optAppend self.btnBoxOkCancel = QDialogButtonBox(self) self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel")) self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) # btnOK = self.btnBoxOkCancel.button(QDialogButtonBox.Ok) # btnOK.setText("Create") self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg) self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject) verticalLayoutDlg.addWidget(self.btnBoxOkCancel) def acceptDlg(self): self.accept() @staticmethod def smethod_0(listInsertPosition_0): flag = False dlgAixmInsertLeg = DlgAixmInsertLeg() if (listInsertPosition_0 == ListInsertPosition.Before): dlgAixmInsertLeg.optBefore.setChecked(True) elif (listInsertPosition_0 != ListInsertPosition.After): dlgAixmInsertLeg.optAppend.setChecked(True) else: dlgAixmInsertLeg.optAfter.setChecked(True) resultDlg = dlgAixmInsertLeg.exec_() if (resultDlg != 1): flag = False else: if (dlgAixmInsertLeg.optBefore.isChecked()): listInsertPosition_0 = ListInsertPosition.Before elif (not dlgAixmInsertLeg.optAfter.isChecked()): listInsertPosition_0 = ListInsertPosition.Append else: listInsertPosition_0 = ListInsertPosition.After flag = True return flag, listInsertPosition_0
def restore_or_create(self): vbox = QVBoxLayout() main_label = QLabel(_("Electrum-VCN could not find an existing wallet.")) vbox.addWidget(main_label) grid = QGridLayout() grid.setSpacing(5) gb1 = QGroupBox(_("What do you want to do?")) vbox.addWidget(gb1) vbox1 = QVBoxLayout() gb1.setLayout(vbox1) b1 = QRadioButton(gb1) b1.setText(_("Create new wallet")) b1.setChecked(True) b2 = QRadioButton(gb1) b2.setText(_("Restore a wallet or import keys")) group1 = QButtonGroup() group1.addButton(b1) group1.addButton(b2) vbox1.addWidget(b1) vbox1.addWidget(b2) gb2 = QGroupBox(_("Wallet type:")) vbox.addWidget(gb2) vbox2 = QVBoxLayout() gb2.setLayout(vbox2) group2 = QButtonGroup() self.wallet_types = [ ('standard', _("Standard wallet")), ('twofactor', _("Wallet with two-factor authentication")), ('multisig', _("Multi-signature wallet")), ('hardware', _("Hardware wallet")), ] for i, (wtype, name) in enumerate(self.wallet_types): if not filter(lambda x: x[0] == wtype, electrum.wallet.wallet_types): continue button = QRadioButton(gb2) button.setText(name) vbox2.addWidget(button) group2.addButton(button) group2.setId(button, i) if i == 0: button.setChecked(True) vbox.addStretch(1) self.set_layout(vbox) vbox.addLayout(Buttons(CancelButton(self), OkButton(self, _('Next')))) self.show() self.raise_() if not self.exec_(): return None, None action = 'create' if b1.isChecked() else 'restore' wallet_type = self.wallet_types[group2.checkedId()][0] return action, wallet_type
class GCPluginConfigDialog(QDialog): " Garbage collector config dialog " SILENT = 0 STATUS_BAR = 1 LOG = 2 def __init__(self, where, parent=None): QDialog.__init__(self, parent) self.__createLayout() self.setWindowTitle("Garbage collector plugin configuration") if where == GCPluginConfigDialog.SILENT: self.__silentRButton.setChecked(True) elif where == GCPluginConfigDialog.STATUS_BAR: self.__statusbarRButton.setChecked(True) else: self.__logtabRButton.setChecked(True) self.__OKButton.setFocus() return def __createLayout(self): """ Creates the dialog layout """ self.resize(450, 150) self.setSizeGripEnabled(True) verticalLayout = QVBoxLayout(self) whereGroupbox = QGroupBox(self) whereGroupbox.setTitle("Garbage collector message destination") sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( whereGroupbox.sizePolicy().hasHeightForWidth()) whereGroupbox.setSizePolicy(sizePolicy) layoutWhere = QVBoxLayout(whereGroupbox) self.__silentRButton = QRadioButton(whereGroupbox) self.__silentRButton.setText("Silent") layoutWhere.addWidget(self.__silentRButton) self.__statusbarRButton = QRadioButton(whereGroupbox) self.__statusbarRButton.setText("Status bar") layoutWhere.addWidget(self.__statusbarRButton) self.__logtabRButton = QRadioButton(whereGroupbox) self.__logtabRButton.setText("Log tab") layoutWhere.addWidget(self.__logtabRButton) verticalLayout.addWidget(whereGroupbox) buttonBox = QDialogButtonBox(self) buttonBox.setOrientation(Qt.Horizontal) buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.__OKButton = buttonBox.button(QDialogButtonBox.Ok) self.__OKButton.setDefault(True) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.close) verticalLayout.addWidget(buttonBox) return def getCheckedOption(self): " Returns what destination is selected " if self.__silentRButton.isChecked(): return GCPluginConfigDialog.SILENT if self.__statusbarRButton.isChecked(): return GCPluginConfigDialog.STATUS_BAR return GCPluginConfigDialog.LOG
class QuickPlotDialog(OkCancelDialog): ''' Quick plot setup dialog ''' SHOW_LOGS_IN_WELL = "Show logs in well" SHOW_LOGS_IN_LOG_SET = "Show logs in log set" SHOW_ALL_LOG_TYPES = "Show all log types" EXISTING_LOG_TYPES_MESSAGE = "Existing log types in black" def __init__(self, logs, well, quickTemplateName, logSet = None, parent=None): super(QuickPlotDialog, self).__init__(parent) self._logs = logs self._well = well self._quickTemplateName = quickTemplateName self._logSet = None self._template = None self._dataListToListWidget = None #show either logs or log types in left view self._logTypesInLeftView = False self.logsInWellRadioButton = None self.allLogTypesRadioButton = None self.generateTemplate() self.addWidgets() self.populateInitialData() self.connectSlots() def generateTemplate(self): #easier to use the WellPlotType for QUICKPLOT than database if self._quickTemplateName == WellPlotType.QUICKPLOT.name: quickPlotUid = WellPlotType.QUICKPLOT.uid elif self._quickTemplateName == WellPlotType.ALLLOGS.name: quickPlotUid = WellPlotType.ALLLOGS.uid elif self._quickTemplateName == WellPlotType.ACTIVELOGS.name: quickPlotUid = WellPlotType.ACTIVELOGS.uid elif self._quickTemplateName == WellPlotType.EMPTY.name: quickPlotUid = WellPlotType.EMPTY.uid else: logger.error("--handleQuickPlotChecked() no match for quickTemplateName: {0}".format(self._quickTemplateName)) if AppSettings.isDebugMode: raise ValueError self._template = WellPlotTemplateDao.getWellPlotTemplateFromUid(quickPlotUid) def templateLogic(self): quickPlotUid = WellPlotType.QUICKPLOT.uid if self._template is None: logger.debug("No template found for uid:{0}".format(quickPlotUid)) else: self._template.trackDataList = self.createQuickLogTypeMatrix() def addWidgets(self): self._dataListToListWidget = DataListToListWidget() vbox = QVBoxLayout() self.placeholderWidget.setLayout(vbox) vbox.addWidget(self._dataListToListWidget) self.addLogOrLogTypeOption() def addLogOrLogTypeOption(self): self.logsInWellRadioButton = QRadioButton() if self._logSet is None: self.logsInWellRadioButton.setText(self.SHOW_LOGS_IN_WELL) else: self.logsInWellRadioButton.setText(self.SHOW_LOGS_IN_LOG_SET) self.allLogTypesRadioButton = QRadioButton() self.allLogTypesRadioButton.setText(self.SHOW_ALL_LOG_TYPES) topButtonLayout = QHBoxLayout() self._dataListToListWidget.topButtonHolderWidget.setLayout(topButtonLayout) topButtonLayout.addWidget(self.logsInWellRadioButton) topButtonLayout.addWidget(self.allLogTypesRadioButton) topButtonGroup = QButtonGroup() topButtonGroup.addButton(self.logsInWellRadioButton) topButtonGroup.addButton(self.allLogTypesRadioButton) self.logsInWellRadioButton.setChecked(True) def populateInitialData(self): if self._logTypesInLeftView: self.logsInWellRadioButton.setChecked(True) self.logsInWellButtonClicked() self._dataListToListWidget.leftDataTypeListView.setToolTip(self.EXISTING_LOG_TYPES_MESSAGE) else: self.allLogTypesRadioButton.setChecked(True) self.allLogTypesButtonClicked() def generateLeftListLogModel(self): '''Returns log model using all logs in self._logs ''' model = QStandardItemModel(self._dataListToListWidget.leftDataTypeListView) for log in self._logs: item = QStandardItem(log.name) # checkboxes are confusing item.setCheckable(False) model.appendRow(item) return model def generateLeftListLogTypeModel(self): '''Returns all LogType list model ''' existingLogTypes = [] logType = LogType.GAMMA #get type for each log if self._logs is not None and len(self._logs)>0: for log in self._logs: existingLogTypes.append(log.log_type_name) generalSettings = GeneralSettings() if generalSettings.workflowType == WorkflowType.petrophysics: logTypeList = logType.getAllLogTypesPetrophysicsStringList() elif generalSettings.workflowType == WorkflowType.rockphysics: logTypeList = logType.getAllLogTypesRockPhysicsStringList() else: logTypeList = logType.getAllLogTypesStringList() model = QStandardItemModel(self._dataListToListWidget.leftDataTypeListView) for logType in logTypeList: item = QStandardItem(logType) # checkboxes are confusing item.setCheckable(False) if logType not in existingLogTypes: item.setForeground(Qt.gray) model.appendRow(item) return model def createQuickLogTypeMatrix(self): logTypeMatrix = [] for typeName in self.getRightListViewStrings(): logTypeMatrix.append([typeName]) return logTypeMatrix def logsInWellButtonClicked(self): leftModel = self.generateLeftListLogModel() self._dataListToListWidget.setLeftModel(leftModel) self._dataListToListWidget.rightListView.setModel(None) def allLogTypesButtonClicked(self): leftModel = self.generateLeftListLogTypeModel() self._dataListToListWidget.setLeftModel(leftModel) self._dataListToListWidget.rightListView.setModel(None) def connectSlots(self): self.logsInWellRadioButton.clicked.connect(self.logsInWellButtonClicked) self.allLogTypesRadioButton.clicked.connect(self.allLogTypesButtonClicked) def accept(self): if (self._dataListToListWidget.rightListView.model() is None) or (self._dataListToListWidget.rightListView.model().rowCount() == 0): logger.info("Please select logs to plot to continue") else: #need to connect WellPlotMPL to main application so can receive signals centralTabWidget = CentralTabWidget() wellPlotPG = WellPlotPG(logs= self._logs, well = self._well, template = self._template, logSet = self._logSet, parent = centralTabWidget) self.close()
class NewDocument(preferences.Group): def __init__(self, page): super(NewDocument, self).__init__(page) grid = QGridLayout() self.setLayout(grid) def changed(): self.changed.emit() self.combo.setEnabled(self.template.isChecked()) self.emptyDocument = QRadioButton(toggled=changed) self.lilyVersion = QRadioButton(toggled=changed) self.template = QRadioButton(toggled=changed) self.combo = QComboBox(currentIndexChanged=changed) grid.addWidget(self.emptyDocument, 0, 0, 1, 2) grid.addWidget(self.lilyVersion, 1, 0, 1, 2) grid.addWidget(self.template, 2, 0, 1, 1) grid.addWidget(self.combo, 2, 1, 1, 1) self.loadCombo() app.translateUI(self) def translateUI(self): self.setTitle(_("When creating new documents")) self.emptyDocument.setText(_("Create an empty document")) self.lilyVersion.setText( _("Create a document that contains the LilyPond version statement") ) self.template.setText(_("Create a document from a template:")) from snippet import snippets for i, name in enumerate(self._names): self.combo.setItemText(i, snippets.title(name)) def loadCombo(self): from snippet import snippets self._names = [ name for name in snippets.names() if snippets.get(name).variables.get('template') ] self.combo.clear() self.combo.addItems([''] * len(self._names)) def loadSettings(self): s = QSettings() ndoc = s.value("new_document", "empty", type("")) template = s.value("new_document_template", "", type("")) if template in self._names: self.combo.setCurrentIndex(self._names.index(template)) if ndoc == "template": self.template.setChecked(True) elif ndoc == "version": self.lilyVersion.setChecked(True) else: self.emptyDocument.setChecked(True) def saveSettings(self): s = QSettings() if self._names and self.template.isChecked(): s.setValue("new_document", "template") s.setValue("new_document_template", self._names[self.combo.currentIndex()]) elif self.lilyVersion.isChecked(): s.setValue("new_document", "version") else: s.setValue("new_document", "empty")
class ShortcutEditDialog(QDialog): """A modal dialog to view and/or edit keyboard shortcuts.""" def __init__(self, parent=None, conflictCallback=None, *cbArgs): """conflictCallback is a optional method called when a shortcut is changed. cbArgs is optional arguments of the conflictCallback method. it should return the name of the potential conflict or a null value """ super(ShortcutEditDialog, self).__init__(parent) self.conflictCallback = conflictCallback self.cbArgs = cbArgs self.setMinimumWidth(400) # create gui layout = QVBoxLayout() layout.setSpacing(10) self.setLayout(layout) top = QHBoxLayout() top.setSpacing(4) p = self.toppixmap = QLabel() l = self.toplabel = QLabel() top.addWidget(p) top.addWidget(l, 1) layout.addLayout(top) grid = QGridLayout() grid.setSpacing(4) grid.setColumnStretch(1, 2) layout.addLayout(grid) self.buttonDefault = QRadioButton(self, toggled=self.slotButtonDefaultToggled) self.buttonNone = QRadioButton(self) self.lconflictDefault = QLabel('test') self.lconflictDefault.setStyleSheet("color : red;") self.lconflictDefault.setVisible(False) self.buttonCustom = QRadioButton(self) grid.addWidget(self.buttonDefault, 0, 0, 1, 2) grid.addWidget(self.lconflictDefault, 1, 0, 1, 2) grid.addWidget(self.buttonNone, 2, 0, 1, 2) grid.addWidget(self.buttonCustom, 3, 0, 1, 2) self.keybuttons = [] self.keylabels = [] self.conflictlabels = [] for num in range(4): l = QLabel(self) l.setStyleSheet("margin-left: 2em;") l.setAlignment(Qt.AlignRight | Qt.AlignVCenter) b = KeySequenceWidget(self, num) b.keySequenceChanged.connect(self.slotKeySequenceChanged) l.setBuddy(b) self.keylabels.append(l) self.keybuttons.append(b) grid.addWidget(l, num+4+num, 0) grid.addWidget(b, num+4+num, 1) lconflict = QLabel() lconflict.setStyleSheet("color : red;") self.conflictlabels.append(lconflict) lconflict.setVisible(False) grid.addWidget(lconflict, num+5+num, 0, 1, 2, Qt.AlignHCenter) layout.addWidget(Separator(self)) b = QDialogButtonBox(self) b.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) layout.addWidget(b) b.accepted.connect(self.accept) b.rejected.connect(self.reject) app.translateUI(self) def translateUI(self): self.setWindowTitle(app.caption(_("window title", "Edit Shortcut"))) self.buttonNone.setText(_("&No shortcut")) self.buttonCustom.setText(_("Use a &custom shortcut:")) for num in range(4): self.keylabels[num].setText(_("Alternative #{num}:").format(num=num) if num else _("Primary shortcut:")) def slotKeySequenceChanged(self, num): """Called when one of the keysequence buttons has changed.""" self.checkConflict(num) self.buttonCustom.setChecked(True) def slotButtonDefaultToggled(self, val): if self.conflictCallback is not None: if not val: self.lconflictDefault.setVisible(False) else: if self._default: conflictList = [] for s in self._default: conflictName = self.conflictCallback(s, *self.cbArgs) if conflictName: conflictList.append(conflictName) if conflictList: text = _("Conflict with: {name}").format( name="<b>{0}</b>".format(', '.join(conflictList))) self.lconflictDefault.setText(text) self.lconflictDefault.setVisible(True) QTimer.singleShot(0, self.adjustSize) def checkConflict(self, num): if self.conflictCallback is not None: conflictName = self.conflictCallback(self.keybuttons[num].shortcut(), *self.cbArgs) if conflictName: text = _("Conflict with: {name}").format( name="<b>{0}</b>".format(conflictName)) self.conflictlabels[num].setText(text) self.conflictlabels[num].setVisible(True) else: self.conflictlabels[num].setVisible(False) QTimer.singleShot(0, self.adjustSize) def editAction(self, action, default=None): # load the action self._action = action self._default = default self.toplabel.setText('<p>{0}</p>'.format( _("Here you can edit the shortcuts for {name}").format( name='<br/><b>{0}</b>:'.format(action.text())))) self.toppixmap.setPixmap(action.icon().pixmap(32)) shortcuts = action.shortcuts() self.buttonDefault.setVisible(bool(default)) if default is not None and shortcuts == default: self.buttonDefault.setChecked(True) else: if shortcuts: self.buttonCustom.setChecked(True) for num, key in enumerate(shortcuts[:4]): self.keybuttons[num].setShortcut(key) self.checkConflict(num) else: self.buttonNone.setChecked(True) if default: ds = "; ".join(key.toString(QKeySequence.NativeText) for key in default) else: ds = _("no keyboard shortcut", "none") self.buttonDefault.setText(_("Use &default shortcut ({name})").format(name=ds)) return self.exec_() def done(self, result): if result: shortcuts = [] if self.buttonDefault.isChecked(): shortcuts = self._default elif self.buttonCustom.isChecked(): for num in range(4): seq = self.keybuttons[num].shortcut() if not seq.isEmpty(): shortcuts.append(seq) self._action.setShortcuts(shortcuts) super(ShortcutEditDialog, self).done(result)
class Ui_TurnProtectionAndObstacleAssessment(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(435, 580) self.verticalLayout = QVBoxLayout(Form) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.gbGeneral = GroupBox(Form) self.gbGeneral.Caption = "General" self.verticalLayout.addWidget(self.gbGeneral) # self.cmbAerodrome = ComboBoxPanel(self.gbGeneral, True) # self.cmbAerodrome.Caption = "Aerodrome" # self.cmbAerodrome.LabelWidth = 120 # self.gbGeneral.Add = self.cmbAerodrome # # self.cmbRwyDir = ComboBoxPanel(self.gbGeneral, True) # self.cmbRwyDir.Caption = "Runway Direction" # self.cmbRwyDir.LabelWidth = 120 # self.cmbRwyDir.Width = 120 # self.gbGeneral.Add = self.cmbRwyDir self.cmbRnavSpecification = ComboBoxPanel(self.gbGeneral) self.cmbRnavSpecification.Caption = "Rnav Specification" self.cmbRnavSpecification.LabelWidth = 150 self.gbGeneral.Add = self.cmbRnavSpecification self.frameChbThree = Frame(self.gbGeneral, "HL") self.gbGeneral.Add = self.frameChbThree self.chbUseTwoWpt = CheckBox(self.frameChbThree) self.chbUseTwoWpt.Caption = "Use 2 Waypoints" self.frameChbThree.Add = self.chbUseTwoWpt self.chbInsertSymbol = CheckBox(self.frameChbThree) self.chbInsertSymbol.Caption = "Insert Symbol(s)" self.frameChbThree.Add = self.chbInsertSymbol self.chbCatH = CheckBox(self.frameChbThree) self.chbCatH.Caption = "Cat.H" self.frameChbThree.Add = self.chbCatH self.cmbPhaseOfFlight = ComboBoxPanel(self.gbGeneral) self.cmbPhaseOfFlight.Caption = "Phase Of Flight" self.cmbPhaseOfFlight.LabelWidth = 150 self.gbGeneral.Add = self.cmbPhaseOfFlight self.pnlArp = PositionPanel(self.gbGeneral) self.pnlArp.Caption = "Aerodrome Reference Point(ARP)" self.pnlArp.btnCalculater.hide() self.pnlArp.hideframe_Altitude() self.gbGeneral.Add = self.pnlArp self.gbWaypoint1 = GroupBox(self.gbGeneral) self.gbWaypoint1.Caption = "Waypoint1" self.gbGeneral.Add = self.gbWaypoint1 self.cmbType1 = ComboBoxPanel(self.gbWaypoint1) self.cmbType1.Caption = "Type" self.cmbType1.LabelWidth = 150 self.gbWaypoint1.Add = self.cmbType1 self.pnlTolerances = RnavTolerancesPanel(self.gbWaypoint1) self.pnlTolerances.set_Att(Distance(0.8, DistanceUnits.NM)) self.pnlTolerances.set_Xtt(Distance(1, DistanceUnits.NM)) self.pnlTolerances.set_Asw(Distance(2, DistanceUnits.NM)) self.gbWaypoint1.Add = self.pnlTolerances self.pnlWaypoint1 = PositionPanel(self.gbWaypoint1) self.pnlWaypoint1.btnCalculater.hide() self.pnlWaypoint1.hideframe_Altitude() self.gbWaypoint1.Add = self.pnlWaypoint1 self.gbWaypoint2 = GroupBox(self.gbGeneral) self.gbWaypoint2.Caption = "Waypoint2" self.gbGeneral.Add = self.gbWaypoint2 self.cmbType2 = ComboBoxPanel(self.gbWaypoint2) self.cmbType2.Caption = "Type" self.cmbType2.LabelWidth = 150 self.gbWaypoint2.Add = self.cmbType2 self.pnlTolerances2 = RnavTolerancesPanel(self.gbWaypoint2) self.pnlTolerances2.set_Att(Distance(0.8, DistanceUnits.NM)) self.pnlTolerances2.set_Xtt(Distance(1, DistanceUnits.NM)) self.pnlTolerances2.set_Asw(Distance(2, DistanceUnits.NM)) self.gbWaypoint2.Add = self.pnlTolerances2 self.pnlWaypoint2 = PositionPanel(self.gbWaypoint2) self.pnlWaypoint2.btnCalculater.hide() self.pnlWaypoint2.hideframe_Altitude() self.gbWaypoint2.Add = self.pnlWaypoint2 self.frmRadioBtns = Frame(self.gbGeneral, "HL") self.gbGeneral.Add = self.frmRadioBtns self.rdnTF = QRadioButton(self.frmRadioBtns) self.rdnTF.setObjectName("rdnTF") self.rdnTF.setText("TF") self.rdnTF.setChecked(True) self.frmRadioBtns.Add = self.rdnTF self.rdnDF = QRadioButton(self.frmRadioBtns) self.rdnDF.setObjectName("rdnDF") self.rdnDF.setText("DF") self.frmRadioBtns.Add = self.rdnDF self.rdnCF = QRadioButton(self.frmRadioBtns) self.rdnCF.setObjectName("rdnCF") self.rdnCF.setText("CF") self.frmRadioBtns.Add = self.rdnCF self.chbCircularArcs = CheckBox(self.gbGeneral) self.chbCircularArcs.Caption = "Use Circular Arcs Method for Turns <= 30" self.gbGeneral.Add = self.chbCircularArcs self.gbParameters = GroupBox(Form) self.gbParameters.Caption = "Parameters" self.verticalLayout.addWidget(self.gbParameters) self.cmbSelectionMode = ComboBoxPanel(self.gbParameters) self.cmbSelectionMode.Caption = "Selection Mode" self.cmbSelectionMode.LabelWidth = 150 self.gbParameters.Add = self.cmbSelectionMode self.pnlInbound = TrackRadialBoxPanel(self.gbParameters) self.pnlInbound.Caption = "In-bound Track" self.pnlInbound.LabelWidth = 150 self.gbParameters.Add = self.pnlInbound self.pnlOutbound = TrackRadialBoxPanel(self.gbParameters) self.pnlOutbound.Caption = "Out-bound Track" self.pnlOutbound.LabelWidth = 150 self.gbParameters.Add = self.pnlOutbound # icon = QIcon() # icon.addPixmap(QPixmap(_fromUtf8("Resource/coordinate_capture.png")), QIcon.Normal, QIcon.Off) self.pnlIas = SpeedBoxPanel(self.gbParameters) self.pnlIas.Caption = "IAS" self.pnlIas.LabelWidth = 150 self.pnlIas.Value = Speed(250) self.gbParameters.Add = self.pnlIas self.pnlTas = SpeedBoxPanel(self.gbParameters) self.pnlTas.Caption = "TAS" self.pnlTas.Enabled = False self.pnlTas.LabelWidth = 150 self.gbParameters.Add = self.pnlTas self.pnlAltitude = AltitudeBoxPanel(self.gbParameters) self.pnlAltitude.Caption = "Altitude" self.pnlAltitude.LabelWidth = 150 self.pnlAltitude.Value = Altitude(1000) self.gbParameters.Add = self.pnlAltitude self.pnlIsa = NumberBoxPanel(self.gbParameters, "0.0") self.pnlIsa.CaptionUnits = define._degreeStr + "C" self.pnlIsa.Caption = "ISA" self.pnlIsa.LabelWidth = 150 self.pnlIsa.Value = 15 self.gbParameters.Add = self.pnlIsa self.pnlBankAngle = NumberBoxPanel(self.gbParameters, "0.0") self.pnlBankAngle.CaptionUnits = define._degreeStr self.pnlBankAngle.Caption = "Bank Angle" self.pnlBankAngle.LabelWidth = 150 self.pnlBankAngle.Value = 25 self.gbParameters.Add = self.pnlBankAngle self.pnlBankEstTime = NumberBoxPanel(self.gbParameters, "0.0") self.pnlBankEstTime.Caption = "Bank Establishment Time" self.pnlBankEstTime.Value = 1 self.pnlBankEstTime.LabelWidth = 150 self.pnlBankEstTime.Value = 5 self.gbParameters.Add = self.pnlBankEstTime self.pnlPilotTime = NumberBoxPanel(self.gbParameters, "0.0") self.pnlPilotTime.Caption = "Pilot Reaction Time" self.pnlPilotTime.Value = 6 self.pnlPilotTime.LabelWidth = 150 self.gbParameters.Add = self.pnlPilotTime self.pnlWind = WindPanel(self.gbParameters) self.pnlWind.LabelWidth = 145 self.gbParameters.Add = self.pnlWind self.pnlPrimaryMoc = AltitudeBoxPanel(self.gbParameters) self.pnlPrimaryMoc.Caption = "Primary Moc" self.pnlPrimaryMoc.LabelWidth = 150 self.gbParameters.Add = self.pnlPrimaryMoc self.cmbConstructionType = ComboBoxPanel(self.gbParameters) self.cmbConstructionType.Caption = "Construction Type" self.cmbConstructionType.LabelWidth = 150 self.gbParameters.Add = self.cmbConstructionType self.frameMOCmultipiler = Frame(self.gbParameters, "HL") self.gbParameters.Add = self.frameMOCmultipiler self.labelMOCmultipiler = QLabel(self.frameMOCmultipiler) self.labelMOCmultipiler.setMinimumSize(QSize(145, 0)) self.labelMOCmultipiler.setMaximumSize(QSize(145, 16777215)) font = QFont() font.setBold(False) font.setWeight(50) self.labelMOCmultipiler.setFont(font) self.labelMOCmultipiler.setObjectName(_fromUtf8("labelMOCmultipiler")) self.labelMOCmultipiler.setText("MOCmultipiler") self.frameMOCmultipiler.Add = self.labelMOCmultipiler self.mocSpinBox = QSpinBox(self.frameMOCmultipiler) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.mocSpinBox.sizePolicy().hasHeightForWidth()) self.mocSpinBox.setSizePolicy(sizePolicy) self.mocSpinBox.setMinimumSize(QSize(70, 0)) self.mocSpinBox.setMaximumSize(QSize(70, 16777215)) self.mocSpinBox.setMinimum(1) self.mocSpinBox.setObjectName(_fromUtf8("mocSpinBox")) self.frameMOCmultipiler.Add = self.mocSpinBox spacerItem = QSpacerItem(10,10,QSizePolicy.Expanding, QSizePolicy.Minimum) self.frameMOCmultipiler.layoutBoxPanel.addItem(spacerItem) self.chbDrawTolerance = CheckBox(self.gbParameters) self.chbDrawTolerance.Caption = "Draw Waypoint Tolerance" self.gbParameters.Add = self.chbDrawTolerance
class NewDocument(preferences.Group): def __init__(self, page): super(NewDocument, self).__init__(page) grid = QGridLayout() self.setLayout(grid) def changed(): self.changed.emit() self.combo.setEnabled(self.template.isChecked()) self.emptyDocument = QRadioButton(toggled=changed) self.lilyVersion = QRadioButton(toggled=changed) self.template = QRadioButton(toggled=changed) self.combo = QComboBox(currentIndexChanged=changed) grid.addWidget(self.emptyDocument, 0, 0, 1, 2) grid.addWidget(self.lilyVersion, 1, 0, 1, 2) grid.addWidget(self.template, 2, 0, 1, 1) grid.addWidget(self.combo, 2, 1, 1, 1) self.loadCombo() app.translateUI(self) def translateUI(self): self.setTitle(_("When creating new documents")) self.emptyDocument.setText(_("Create an empty document")) self.lilyVersion.setText(_("Create a document that contains the LilyPond version statement")) self.template.setText(_("Create a document from a template:")) from snippet import snippets for i, name in enumerate(self._names): self.combo.setItemText(i, snippets.title(name)) def loadCombo(self): from snippet import snippets self._names = [name for name in snippets.names() if snippets.get(name).variables.get('template')] self.combo.clear() self.combo.addItems([''] * len(self._names)) def loadSettings(self): s = QSettings() ndoc = s.value("new_document", "empty", type("")) template = s.value("new_document_template", "", type("")) if template in self._names: self.combo.setCurrentIndex(self._names.index(template)) if ndoc == "template": self.template.setChecked(True) elif ndoc == "version": self.lilyVersion.setChecked(True) else: self.emptyDocument.setChecked(True) def saveSettings(self): s = QSettings() if self._names and self.template.isChecked(): s.setValue("new_document", "template") s.setValue("new_document_template", self._names[self.combo.currentIndex()]) elif self.lilyVersion.isChecked(): s.setValue("new_document", "version") else: s.setValue("new_document", "empty")
class GCPluginConfigDialog( QDialog ): " Garbage collector config dialog " SILENT = 0 STATUS_BAR = 1 LOG = 2 def __init__( self, where, parent = None ): QDialog.__init__( self, parent ) self.__createLayout() self.setWindowTitle( "Garbage collector plugin configuration" ) if where == GCPluginConfigDialog.SILENT: self.__silentRButton.setChecked( True ) elif where == GCPluginConfigDialog.STATUS_BAR: self.__statusbarRButton.setChecked( True ) else: self.__logtabRButton.setChecked( True ) self.__OKButton.setFocus() return def __createLayout( self ): """ Creates the dialog layout """ self.resize( 450, 150 ) self.setSizeGripEnabled( True ) verticalLayout = QVBoxLayout( self ) whereGroupbox = QGroupBox( self ) whereGroupbox.setTitle( "Garbage collector message destination" ) sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred ) sizePolicy.setHorizontalStretch( 0 ) sizePolicy.setVerticalStretch( 0 ) sizePolicy.setHeightForWidth( whereGroupbox.sizePolicy().hasHeightForWidth() ) whereGroupbox.setSizePolicy( sizePolicy ) layoutWhere = QVBoxLayout( whereGroupbox ) self.__silentRButton = QRadioButton( whereGroupbox ) self.__silentRButton.setText( "Silent" ) layoutWhere.addWidget( self.__silentRButton ) self.__statusbarRButton = QRadioButton( whereGroupbox ) self.__statusbarRButton.setText( "Status bar" ) layoutWhere.addWidget( self.__statusbarRButton ) self.__logtabRButton = QRadioButton( whereGroupbox ) self.__logtabRButton.setText( "Log tab" ) layoutWhere.addWidget( self.__logtabRButton ) verticalLayout.addWidget( whereGroupbox ) buttonBox = QDialogButtonBox( self ) buttonBox.setOrientation( Qt.Horizontal ) buttonBox.setStandardButtons( QDialogButtonBox.Ok | QDialogButtonBox.Cancel ) self.__OKButton = buttonBox.button( QDialogButtonBox.Ok ) self.__OKButton.setDefault( True ) buttonBox.accepted.connect( self.accept ) buttonBox.rejected.connect( self.close ) verticalLayout.addWidget( buttonBox ) return def getCheckedOption( self ): " Returns what destination is selected " if self.__silentRButton.isChecked(): return GCPluginConfigDialog.SILENT if self.__statusbarRButton.isChecked(): return GCPluginConfigDialog.STATUS_BAR return GCPluginConfigDialog.LOG