def view(self): """create view and import layers""" layer = QgsMapLayerRegistry.instance().mapLayer( self.current_layers[0] ) uri = QgsDataSourceURI(layer.source()) mtch = re.match(r'(.+)_([^_]+)_rev_(head|\d+)', uri.schema()) schema = mtch.group(1) assert(schema) dlg = QDialog() layout = QVBoxLayout(dlg) button_box = QDialogButtonBox(dlg) button_box.setStandardButtons( QDialogButtonBox.Cancel|QDialogButtonBox.Ok) button_box.accepted.connect(dlg.accept) button_box.rejected.connect(dlg.reject) pcur = versioning_base.Db( psycopg2.connect(self.pg_conn_info()) ) pcur.execute("SELECT rev, commit_msg, branch, date, author " "FROM "+schema+".revisions") revs = pcur.fetchall() pcur.close() tblw = QTableWidget( dlg ) tblw.setRowCount(len(revs)) tblw.setColumnCount(5) tblw.setSortingEnabled(True) tblw.setHorizontalHeaderLabels(['Revision', 'Commit Message', 'Branch', 'Date', 'Author']) tblw.verticalHeader().setVisible(False) for i, rev in enumerate(revs): for j, item in enumerate(rev): tblw.setItem(i, j, QTableWidgetItem( str(item) )) layout.addWidget( tblw ) layout.addWidget( button_box ) dlg.resize( 600, 300 ) if not dlg.exec_() : return rows = set() for i in tblw.selectedIndexes(): rows.add(i.row()) for row in rows: branch = revs[row][2] rev = revs[row][0] versioning_base.add_revision_view(uri.connectionInfo(), schema, branch, rev ) grp_name = branch+' revision '+str(rev) grp_idx = self.iface.legendInterface().addGroup( grp_name ) for layer_id in reversed(self.current_layers): layer = QgsMapLayerRegistry.instance().mapLayer(layer_id) new_uri = QgsDataSourceURI(layer.source()) new_uri.setDataSource(schema+'_'+branch+'_rev_'+str(rev), new_uri.table(), new_uri.geometryColumn(), new_uri.sql(), new_uri.keyColumn()) display_name = QgsMapLayerRegistry.instance().mapLayer(layer_id).name() src = new_uri.uri().replace('()','') new_layer = self.iface.addVectorLayer( src, display_name, 'postgres') self.iface.legendInterface().moveLayer( new_layer, grp_idx)
class Dial(QDialog): choices =['flat', 'hanning', 'hamming', 'bartlett', 'blackman'] def __init__(self, parent): QDialog.__init__(self, parent) f =QFormLayout(self) self.a =QSpinBox(self) self.a.setValue(30) self.b = QComboBox(self) self.b.addItems(self.choices) self.c= QDialogButtonBox(self) self.c.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) f.addRow("window:" ,self.a) f.addRow("method:", self.b) f.addRow("", self.c) self.connect(self.c, SIGNAL("accepted()"), self.sendData) self.connect(self.c, SIGNAL("rejected()"), self.reinitialize) def sendData(self): self.parent().window = self.a.value() self.parent().method = self.b.currentText() self.close() def reinitialize(self): self.parent().window = None self.parent().method = None self.close()
def __init__(self, password, parent=None): super(AuthenDlg, self).__init__(parent) self.setWindowTitle('Authentication') self.password = password layout = QGridLayout(self) desc = QLabel() if self.password != "":#authentication is required only once Once it is correct desc.setText("Caution! your action will be recorded on the logbook\n \ Click OK if you want to continue, otherwise click Cancel") else: desc.setText("Your action will be recorded on the logbook\n \ Please enter your password if you want to continue\n \ Otherwise Click Cancel \n") self.passWdLineEdit = QLineEdit() self.passWdLineEdit.setEchoMode(QLineEdit.Password) vbox = QVBoxLayout() vbox.addWidget(self.passWdLineEdit) vbox.addStretch(1) QObject.connect(self.passWdLineEdit, SIGNAL(_fromUtf8("textChanged(QString)")), self.getPassWd) layout.addWidget(self.passWdLineEdit,1,0,1,1) buttonBox = QDialogButtonBox() buttonBox.setOrientation(Qt.Horizontal) buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) QObject.connect(buttonBox, SIGNAL("rejected()"), self.reject) QObject.connect(buttonBox, SIGNAL("accepted()"), self.accept) layout.addWidget(desc,0,0,1,1) layout.addWidget(buttonBox,2,0,1,1) self.setLayout(layout)
class DateRangeDialog(QDialog): def __init__(self): super(DateRangeDialog, self).__init__() self._fro = QDateEdit(datetime.date.today()) self._to = QDateEdit(datetime.date.today() + datetime.timedelta(4)) self._fro.dateChanged.connect(self._check_valid_range) self._to.dateChanged.connect(self._check_valid_range) self.buttons = QDialogButtonBox(QDialogButtonBox.Ok) self.buttons.accepted.connect(self.accept) layout = QVBoxLayout() layout.addWidget(QLabel('Please select a date range')) layout.addWidget(self._fro) layout.addWidget(self._to) layout.addWidget(self.buttons) self.setLayout(layout) def _check_valid_range(self): self.buttons.button(QDialogButtonBox.Ok)\ .setEnabled(self._fro.date() <= self._to.date()) @property def fro(self): return self._fro.date().toPyDate() @property def to(self): return self._to.date().toPyDate()
def __init__(self, interface, net=None, parent=None): CentralDialog.__init__(self, parent) self.net=net self.interface = interface self.editor = NetFrame(interface, net=net) #easy accessors self.net_label = self.editor.net_label self.ip_addrs = self.editor.ip_addrs self.net_ip = self.editor.net_ip button_box = QDialogButtonBox() button_box.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok |QDialogButtonBox.Help) self.ok_button = button_box.Ok self.connectButtons(button_box) #layout box = QVBoxLayout(self) box.addWidget(self.editor) box.addWidget(button_box) self.connect(self.editor, SIGNAL("change title"), self.changeTitle) self.editor.changeTitle() self.acceptableInput()
class GoogleFinanceUrlSetupDialog(QDialog): SETTING_GOOGLE_URL = 'googleUrl' SETTING_GOOGLE_COUNTRY = 'googleCountry' def __init__(self, parent): QDialog.__init__(self, parent) self.prop = MaeMoneyProperties.instance() self.urls = {} self.urls[self.prop.GOOGLE_COUNTRY_HK] = 'www.google.com.hk' self.urls[self.prop.GOOGLE_COUNTRY_CN] = 'www.google.com.cn' self.urls[self.prop.GOOGLE_COUNTRY_CAN] = 'www.google.ca' self.urls[self.prop.GOOGLE_COUNTRY_UK] = 'www.google.co.uk' self.urls[self.prop.GOOGLE_COUNTRY_US] = 'www.google.com' self.setupUi() def setupUi(self): self.setWindowModality(Qt.WindowModal) self.buttonBox = QDialogButtonBox(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.gridLayout = QGridLayout() self.setLayout(self.gridLayout) self.labelGFinanceUrl = QLabel(self.tr("Google URL")) self.gridLayout.addWidget(self.labelGFinanceUrl, 0, 1, 1, 1) self.comboBoxGFinanceUrl = QComboBox() for [country, url] in sorted(self.urls.iteritems()): self.comboBoxGFinanceUrl.addItem(country, url) googleCountry = self.prop.getGoogleCountry() index = self.comboBoxGFinanceUrl.findText(googleCountry) self.comboBoxGFinanceUrl.setCurrentIndex(index) self.gridLayout.addWidget(self.comboBoxGFinanceUrl, 0, 2, 1, 1) self.gridLayout.addWidget(QLabel(self.tr("Current setting")), 1, 1, 1, 1) self.gridLayout.addWidget(QLabel(self.prop.getGoogleCountry()), 1, 2, 1, 1) self.setUrlButton = QPushButton(self.tr("Set URL")) self.gridLayout.addWidget(self.setUrlButton, 2, 1, 1, 2) self.loginErrorMsgLabel = QLabel("") self.gridLayout.addWidget(self.loginErrorMsgLabel, 3, 1, 1, 2) self.setWindowTitle(self.tr("Setup")) self.connect(self.buttonBox, SIGNAL("accepted()"), self.accept) self.connect(self.buttonBox, SIGNAL("rejected()"), self.reject) self.connect(self.setUrlButton, SIGNAL("clicked()"), self.setUrl) def setUrl(self): indexSelected = self.comboBoxGFinanceUrl.currentIndex() country = self.comboBoxGFinanceUrl.itemText(indexSelected) url = self.comboBoxGFinanceUrl.itemData(indexSelected).toString().toAscii() self.prop.setGoogleCountryUrl(country, url) self.accept()
def __init__(self, opPixelClassification, parent): super( QDialog, self ).__init__(parent=parent) self._op = opPixelClassification classifier_listwidget = QListWidget(parent=self) classifier_listwidget.setSelectionMode( QListWidget.SingleSelection ) classifier_factories = self._get_available_classifier_factories() for name, classifier_factory in classifier_factories.items(): item = QListWidgetItem( name ) item.setData( Qt.UserRole, QVariant(classifier_factory) ) classifier_listwidget.addItem(item) buttonbox = QDialogButtonBox( Qt.Horizontal, parent=self ) buttonbox.setStandardButtons( QDialogButtonBox.Ok | QDialogButtonBox.Cancel ) buttonbox.accepted.connect( self.accept ) buttonbox.rejected.connect( self.reject ) layout = QVBoxLayout() layout.addWidget( classifier_listwidget ) layout.addWidget( buttonbox ) self.setLayout(layout) self.setWindowTitle( "Select Classifier Type" ) # Save members self._classifier_listwidget = classifier_listwidget
def __init__(self, parent, url, archivo_destino): super(Descargar, self).__init__(parent) self.url = url self.httpGetId = 0 self.httpRequestAborted = False self.statusLabel = QLabel('Descargando el manual completo ...') self.closeButton = QPushButton("Cerrar") self.closeButton.setAutoDefault(False) self.barra = QProgressBar() buttonBox = QDialogButtonBox() buttonBox.addButton(self.closeButton, QDialogButtonBox.RejectRole) self.http = QHttp(self) self.http.requestFinished.connect(self.cuando_finalizar_request) self.http.dataReadProgress.connect(self.cuando_actualiza_descarga) self.http.responseHeaderReceived.connect(self.cuando_responder_header) self.closeButton.clicked.connect(self.cuando_cancela) mainLayout = QVBoxLayout() mainLayout.addWidget(self.statusLabel) mainLayout.addWidget(self.barra) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.setWindowTitle('Descargando manual') self.downloadFile(url, archivo_destino)
def fill(self): # Vispa # icon # Version # Release date os.path.getmtime(filename) # website url # license self.setLayout(QVBoxLayout()) if "vispa" in self._application.windowTitle().lower(): self._logo = QSvgWidget(":/resources/vispa_logo.svg") sizeHint = self._logo.sizeHint() logo_width_height_ratio = 1.0 * sizeHint.width() / sizeHint.height() logo_width = 200 self._logo.setFixedSize(logo_width, logo_width/logo_width_height_ratio) self.layout().addWidget(self._logo) else: label=QLabel(self._application.windowTitle()) self.layout().addWidget(label) self.layout().addWidget(QLabel("Version "+ self._application.version())) self.layout().addWidget(QLabel("More information can be found on:")) websiteLink = QLabel("<a href='"+ websiteUrl +"'>"+ websiteUrl +"</a>") websiteLink.setTextInteractionFlags(Qt.LinksAccessibleByMouse | Qt.TextSelectableByMouse) websiteLink.setOpenExternalLinks(True) self.layout().addWidget(websiteLink) buttonBox=QDialogButtonBox() buttonBox.addButton(QDialogButtonBox.Close) self.connect(buttonBox,SIGNAL("rejected()"),self,SLOT("reject()")) self.layout().addWidget(buttonBox)
def __createLayout( self ): """ Creates the dialog layout """ self.resize( 450, 20 ) self.setSizeGripEnabled( True ) verticalLayout = QVBoxLayout( self ) # Info label self.infoLabel = QLabel( self ) verticalLayout.addWidget( self.infoLabel ) # Progress bar self.progressBar = QProgressBar( self ) self.progressBar.setValue( 0 ) self.progressBar.setOrientation( Qt.Horizontal ) verticalLayout.addWidget( self.progressBar ) # Buttons buttonBox = QDialogButtonBox( self ) buttonBox.setOrientation( Qt.Horizontal ) buttonBox.setStandardButtons( QDialogButtonBox.Close ) verticalLayout.addWidget( buttonBox ) buttonBox.rejected.connect( self.__onClose ) return
class SimpleRichTypesDialog(QDialog): """Simple dialog to display and change RichTypes""" def __init__(self, parent=None, windowTitle='', scrolling=True, text=''): QDialog.__init__(self, parent) self.mainLayout = QVBoxLayout(self) self.textLabel = QLabel(self) self.textLabel.setText(text) self.mainLayout.addWidget(self.textLabel) if scrolling: self.scrollArea = QScrollArea(self) self.mainLayout.addWidget(self.scrollArea) self.richTypesWidget = RichTypesWidget(self.scrollArea) self.scrollArea.setWidget(self.richTypesWidget) self.scrollArea.setWidgetResizable(False) else: self.richTypesWidget = RichTypesWidget(self) self.mainLayout.addWidget(self.richTypesWidget) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.NoButton | QDialogButtonBox.Ok) self.mainLayout.addWidget(self.buttonBox) QObject.connect(self.buttonBox, SIGNAL('accepted()'), self.accept) QObject.connect(self.buttonBox, SIGNAL('rejected()'), self.reject) self.setWindowTitle(windowTitle) self.result = None def addRichTypes(self, l): """set the list of richtypes""" self.richTypesWidget.addRichTypes(l) def accept(self): """after dialog closes, RichType list is available as self.result""" self.result = self.richTypesWidget.applyChanges() QDialog.accept(self)
def __init__(self, url_to_download, download_location, parent=None): super(Downloader, self).__init__(parent) self.httpGetId = 0 self.httpRequestAborted = False self.statusLabel = QLabel('Downloading %s' % url_to_download) self.closeButton = QPushButton("Close") self.closeButton.setAutoDefault(False) self.progressBar = QProgressBar() buttonBox = QDialogButtonBox() buttonBox.addButton(self.closeButton, QDialogButtonBox.RejectRole) self.http = QHttp(self) self.http.requestFinished.connect(self.httpRequestFinished) self.http.dataReadProgress.connect(self.updateDataReadProgress) self.http.responseHeaderReceived.connect(self.readResponseHeader) self.closeButton.clicked.connect(self.cancelDownload) mainLayout = QVBoxLayout() mainLayout.addWidget(self.statusLabel) mainLayout.addWidget(self.progressBar) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.setWindowTitle('Downloader') self.downloadFile(url_to_download, download_location)
class Login(QDialog): def __init__(self, parent=None): QDialog.__init__(self) self.parent = parent self.resize(270, 160) self.verticalLayout = QVBoxLayout(self) self.label_username = QLabel(self) self.verticalLayout.addWidget(self.label_username) self.username = QLineEdit(self) self.verticalLayout.addWidget(self.username) self.label_password = QLabel(self) self.verticalLayout.addWidget(self.label_password) self.password = QLineEdit(self) self.password.setEchoMode(QLineEdit.Password) self.verticalLayout.addWidget(self.password) self.save_password = QCheckBox(self) self.verticalLayout.addWidget(self.save_password) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons( QDialogButtonBox.Cancel|QDialogButtonBox.Ok) self.verticalLayout.addWidget(self.buttonBox) self.label_username.setBuddy(self.username) self.label_password.setBuddy(self.password) self.setWindowIcon(get_icon(MAIL_IMAGE)) self.setWindowTitle("Gmail Login") self.label_username.setText("Username") self.label_password.setText("Password") self.save_password.setText("Save password") self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject)
class SearchDialog(utils.Dialog): def __init__(self, main_win, hex_widget): utils.Dialog.__init__(self, main_win, name='search_dialog') self.hexWidget = hex_widget self.setWindowTitle(utils.tr('Search')) self.m_layout = QVBoxLayout() self.setLayout(self.m_layout) self.descLabel = QLabel(self) self.descLabel.setText(utils.tr('Enter hex values to search for:')) self.m_layout.addWidget(self.descLabel) self.hexInput = hexlineedit.HexLineEdit(self) self.m_layout.addWidget(self.hexInput) self.buttonBox = QDialogButtonBox(self) self.buttonBox.addButton(QDialogButtonBox.Close) self.searchButton = QPushButton(utils.tr('Search'), self) self.searchButton.setIcon(utils.getIcon('edit-find')) self.buttonBox.addButton(self.searchButton, QDialogButtonBox.AcceptRole) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.m_layout.addWidget(self.buttonBox) @property def matcher(self): return matchers.BinaryMatcher(self.hexWidget.document, self.hexInput.data)
def __init__(self, data, title="", comment="", icon=None, parent=None, apply=None): super(FormDialog, self).__init__(parent) self.apply_callback = apply # Form if isinstance(data[0][0], (list, tuple)): self.formwidget = FormTabWidget(data, comment=comment, parent=self) elif len(data[0])==3: self.formwidget = FormComboWidget(data, comment=comment, parent=self) else: self.formwidget = FormWidget(data, comment=comment, parent=self) layout = QVBoxLayout() layout.addWidget(self.formwidget) # Button box bbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) if self.apply_callback is not None: apply_btn = bbox.addButton(QDialogButtonBox.Apply) self.connect(apply_btn, SIGNAL("clicked()"), self.apply) self.connect(bbox, SIGNAL("accepted()"), SLOT("accept()")) self.connect(bbox, SIGNAL("rejected()"), SLOT("reject()")) layout.addWidget(bbox) self.setLayout(layout) self.setWindowTitle(title) if not isinstance(icon, QIcon): icon = QWidget().style().standardIcon(QStyle.SP_MessageBoxQuestion) self.setWindowIcon(icon)
def __setupUi(self): layout = QVBoxLayout() # Scene with the link editor. self.scene = LinksEditScene() self.view = QGraphicsView(self.scene) self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.view.setRenderHint(QPainter.Antialiasing) self.scene.editWidget.geometryChanged.connect(self.__onGeometryChanged) # Ok/Cancel/Clear All buttons. buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel | QDialogButtonBox.Reset, Qt.Horizontal) clear_button = buttons.button(QDialogButtonBox.Reset) clear_button.setText(self.tr("Clear All")) buttons.accepted.connect(self.accept) buttons.rejected.connect(self.reject) clear_button.clicked.connect(self.scene.editWidget.clearLinks) layout.addWidget(self.view) layout.addWidget(buttons) self.setLayout(layout) layout.setSizeConstraint(QVBoxLayout.SetFixedSize) self.setSizeGripEnabled(False)
def __init__(self, channel_names, feature_names, default_selections=None, parent=None): """ Parameters ---------- channel_names *list of str* The user will be shown a separate checklist of feature options for each channel. feature_names *list of str* Feature names, exactly as expected by :py:meth:`~ilastikrag.rag.Rag.compute_features()`. The features will be grouped by category and shown in duplicate checklist widgets for each channel. default_selections *dict, str: list-of-str* Mapping from channel_name -> feature_names, indicating which features should be selected by default for each channel. parent *QWidget* """ super(FeatureSelectionDialog, self).__init__(parent) self.setWindowTitle("Select Edge Features") self.tree_widgets = {} self.checklist_widgets = OrderedDict() boxes_layout = QHBoxLayout() for channel_name in channel_names: default_checked = [] if default_selections and channel_name in default_selections: default_checked = default_selections[channel_name] checklist = _make_checklist(feature_names, default_checked) checklist.name = channel_name checklist_widget = HierarchicalChecklistView( checklist, parent=self ) self.checklist_widgets[channel_name] = checklist_widget boxes_layout.addWidget(checklist_widget) buttonbox = QDialogButtonBox( Qt.Horizontal, parent=self ) buttonbox.setStandardButtons( QDialogButtonBox.Ok | QDialogButtonBox.Cancel ) buttonbox.accepted.connect( self.accept ) buttonbox.rejected.connect( self.reject ) widget_layout = QVBoxLayout() # FIXME: Would like to hold the TreeWidgets in a QScrollArea, # but they don't seem to respect fixed size policies, # so the scroll area never shows a scrollbar... #scrollarea = QScrollArea() #scrollarea.setLayout(boxes_layout) #widget_layout.addWidget(scrollarea) widget_layout.addLayout(boxes_layout) widget_layout.addWidget(buttonbox) self.setLayout(widget_layout) total_spacing = self.width() - (len(channel_names)*checklist_widget.width()) total_width = total_spacing + len(channel_names) * ( 20 + checklist_widget.columnWidth(0) ) self.resize(total_width, 500)
class NewProjectDirDialog( QDialog, object ): " New project directory dialog " def __init__( self, parent = None ): QDialog.__init__( self, parent ) self.__dirnameEdit = None self.__buttonBox = None self.__createLayout() self.okButton = self.__buttonBox.button( QDialogButtonBox.Ok ) self.okButton.setEnabled( False ) return def __createLayout( self ): " Creates the dialog layout " self.resize( 400, 100 ) self.setWindowTitle( "Create subdirectory" ) vboxlayout = QVBoxLayout( self ) inputLabel = QLabel( self ) inputLabel.setText( "Type new subdirectory name" ) vboxlayout.addWidget( inputLabel ) self.__dirnameEdit = QLineEdit( self ) self.__dirnameEdit.setToolTip( "Subdirectory name without " "path separators" ) self.__dirnameEdit.installEventFilter( self ) self.__dirnameEdit.textEdited.connect( self.__onTextChanged ) vboxlayout.addWidget( self.__dirnameEdit ) self.__buttonBox = QDialogButtonBox( self ) self.__buttonBox.setOrientation( Qt.Horizontal ) self.__buttonBox.setStandardButtons( QDialogButtonBox.Cancel | QDialogButtonBox.Ok ) vboxlayout.addWidget( self.__buttonBox ) self.__buttonBox.accepted.connect( self.accept ) self.__buttonBox.rejected.connect( self.reject ) return def __onTextChanged( self, text ): " Triggered when the input text has been changed " self.okButton.setEnabled( text != "" ) return def getDirName( self ): " Provides the user input " return self.__dirnameEdit.text() def eventFilter( self, obj, event ): " Event filter for the project name field " # Do not allow path separators if event.type() == QEvent.KeyPress: if event.key() == ord( os.path.sep ): return True return QObject.eventFilter( self, obj, event )
class config_window(QDialog): def __init__(self, parent=None): QDialog.__init__(self, parent) self.setMaximumSize(QSize(0, 0)) self.setMinimumSize(500, 0) self.setWindowTitle('Minecraft Backup Manager - Configuration') #STANNDARD BUTTONS self.button_box = QDialogButtonBox(self) self.button_box.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Save) #input_save_folder self.input_save_folder = QLineEdit(self) self.input_save_folder.setText(load_config('save_backup_folder')) self.input_save_folder.setToolTip('Default folder save backup') #change_save_folder self.btn_save_folder = QPushButton('Change', self) #LAYOUTS #Save Folder Layout self.layout_save_folder = QHBoxLayout() self.layout_save_folder.addWidget(QLabel('Save folder:', self)) self.layout_save_folder.addWidget(self.input_save_folder) self.layout_save_folder.addWidget(self.btn_save_folder) #Button Box Layout self.layout_button_box = QHBoxLayout() self.layout_button_box.setContentsMargins(0, 25, 0, 0) self.layout_button_box.addWidget(self.button_box) #Vertical Container Layout self.Vcontainer = QVBoxLayout(self) self.Vcontainer.addLayout(self.layout_save_folder) self.Vcontainer.addLayout(self.layout_button_box) #CONNECT SIGNALS self.connect(self.btn_save_folder, SIGNAL('clicked()'), self.change_save_folder) self.connect(self.button_box, SIGNAL('accepted()'), self.save_configurations) self.connect(self.button_box, SIGNAL('rejected()'), self.close) def change_save_folder(self): self.file_dialog = QFileDialog.getExistingDirectory(self, 'Change Default folder save backup', directory=self.input_save_folder.text()) if self.file_dialog != '': self.input_save_folder.setText(self.file_dialog) def save_configurations(self): self.backup_folder = str(self.input_save_folder.text().toUtf8()) save_new_config(self.backup_folder) self.close()
def __init__(self, configuration_path, parent = None): QDialog.__init__(self, parent) self.setModal(True) self.setWindowTitle("New configuration file") self.setMinimumWidth(250) self.setMinimumHeight(150) layout = QFormLayout() directory, filename = os.path.split(configuration_path) if directory.strip() == "": directory = os.path.abspath(os.curdir) self.configuration_path = "%s/%s" % (directory, filename) else: self.configuration_path = configuration_path configuration_location = QLabel() configuration_location.setText(directory) configuration_name = QLabel() configuration_name.setText(filename) self.db_type = QComboBox() self.db_type.addItem("BLOCK_FS") self.db_type.addItem("PLAIN") self.num_realizations = QSpinBox() self.num_realizations.setMinimum( 1 ) self.num_realizations.setMaximum( 1000 ) self.num_realizations.setValue( 10 ) self.storage_path = QLineEdit() self.storage_path.setText("Storage") self.connect(self.storage_path, SIGNAL('textChanged(QString)'), self._validateName) layout.addRow(createSpace(10)) layout.addRow("Configuration name:", configuration_name) layout.addRow("Configuration location:", configuration_location) layout.addRow("Path to store DBase:",self.storage_path) layout.addRow("DBase type:", self.db_type) layout.addRow("Number of realizations" , self.num_realizations) layout.addRow(createSpace(10)) buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self) self.ok_button = buttons.button(QDialogButtonBox.Ok) layout.addRow(buttons) self.connect(buttons, SIGNAL('accepted()'), self.accept) self.connect(buttons, SIGNAL('rejected()'), self.reject) self.setLayout(layout)
class DialogStudentId(QDialog): """Dialog to change the student id. Example (replace `parent` by the parent widget): dialog = DialogStudentId(parent) id = dialog.exec_() """ def __init__(self, parent, students): super(DialogStudentId, self).__init__(parent) self.setWindowTitle(_('Change the student id')) layout = QFormLayout() self.setLayout(layout) self.combo = widgets.StudentComboBox(parent=self) self.combo.add_students(students) self.combo.editTextChanged.connect(self._check_value) self.combo.currentIndexChanged.connect(self._check_value) new_student_button = QPushButton( \ QIcon(utils.resource_path('new_id.svg')), _('New student'), parent=self) new_student_button.clicked.connect(self._new_student) self.buttons = QDialogButtonBox((QDialogButtonBox.Ok | QDialogButtonBox.Cancel)) self.buttons.addButton(new_student_button, QDialogButtonBox.ActionRole) self.buttons.accepted.connect(self.accept) self.buttons.rejected.connect(self.reject) layout.addRow(_('Student id:'), self.combo) layout.addRow(self.buttons) def exec_(self): """Shows the dialog and waits until it is closed. Returns a student object with the option selected by the user. The return value is None if the user cancels the dialog. """ result = super(DialogStudentId, self).exec_() if result == QDialog.Accepted: return self.combo.current_student() else: return None def _new_student(self): dialog = NewStudentDialog(parent=self) student = dialog.exec_() if student is not None: self.combo.add_student(student, set_current=True) self.buttons.button(QDialogButtonBox.Ok).setFocus() self.buttons.button(QDialogButtonBox.Ok).setEnabled(True) def _check_value(self, param): if self.combo.current_student() is not None: self.buttons.button(QDialogButtonBox.Ok).setEnabled(True) else: self.buttons.button(QDialogButtonBox.Ok).setEnabled(False)
def __init__(self, parent): QDialog.__init__(self, parent) self.tmpPref = {} self.tmpPref['pref'] = copy.deepcopy(self.parent().prm['pref']) self.currLocale = self.parent().prm['currentLocale'] self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator) self.tabWidget = QTabWidget() self.tabWidget.currentChanged.connect(self.tabChanged) self.appPrefWidget = QWidget() #APP PREF appPrefGrid = QGridLayout() n = 0 self.startRecWAVButton = QPushButton("Choose Start Recording WAV:", self) self.startRecWAVButton.clicked.connect(self.onClickStartRecordingWAV) appPrefGrid.addWidget(self.startRecWAVButton, n, 0) self.startRecWAV = QLineEdit() self.startRecWAV.setText(self.tmpPref['pref']['startRecWAV']) appPrefGrid.addWidget(self.startRecWAV, n, 1) n = n+1 self.stopRecWAVButton = QPushButton("Choose Stop Recording WAV:", self) self.stopRecWAVButton.clicked.connect(self.onClickStopRecordingWAV) appPrefGrid.addWidget(self.stopRecWAVButton, n, 0) self.stopRecWAV = QLineEdit() self.stopRecWAV.setText(self.tmpPref['pref']['stopRecWAV']) appPrefGrid.addWidget(self.stopRecWAV, n, 1) n = n+1 self.markBlockWAVButton = QPushButton("Choose Mark Block Beginning WAV:", self) self.markBlockWAVButton.clicked.connect(self.onClickMarkBlockWAV) appPrefGrid.addWidget(self.markBlockWAVButton, n, 0) self.markBlockWAV = QLineEdit() self.markBlockWAV.setText(self.tmpPref['pref']['markBlockWAV']) appPrefGrid.addWidget(self.markBlockWAV, n, 1) n = n+1 self.appPrefWidget.setLayout(appPrefGrid) self.tabWidget.addTab(self.appPrefWidget, self.tr("Applicatio&n")) buttonBox = QDialogButtonBox(QDialogButtonBox.Apply|QDialogButtonBox.Ok|QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) buttonBox.button(QDialogButtonBox.Apply).clicked.connect(self.permanentApply) layout = QVBoxLayout() layout.addWidget(self.tabWidget) layout.addWidget(buttonBox) self.setLayout(layout)
def checkout_pg(self): """create postgres working copy (schema) from versioned database layers""" # for each connection, we need the list of tables tables_for_conninfo = [] uri = None conn_info = '' for layer_id in self.current_layers: layer = QgsMapLayerRegistry.instance().mapLayer( layer_id ) uri = QgsDataSourceURI(layer.source()) if not conn_info: conn_info = uri.connectionInfo() else: assert(conn_info == uri.connectionInfo()) table = uri.schema()+"."+uri.table() tables_for_conninfo.append(table) dlg = QDialog() dlg.setWindowTitle('Enter working copy schema name') layout = QVBoxLayout(dlg) button_box = QDialogButtonBox(dlg) button_box.setStandardButtons( QDialogButtonBox.Cancel|QDialogButtonBox.Ok) button_box.accepted.connect(dlg.accept) button_box.rejected.connect(dlg.reject) line_edit = QLineEdit( dlg ) layout.addWidget( line_edit ) layout.addWidget( button_box ) if not dlg.exec_() : return working_copy_schema = line_edit.text() if not working_copy_schema: print "aborted" return print "checking out ", tables_for_conninfo, " from ", uri.connectionInfo() versioning_base.pg_checkout( self.pg_conn_info(), tables_for_conninfo, working_copy_schema ) # add layers from offline version grp_idx = self.iface.legendInterface().addGroup( working_copy_schema ) for layer_id in reversed(self.current_layers): layer = QgsMapLayerRegistry.instance().mapLayer( layer_id ) new_uri = QgsDataSourceURI(layer.source()) new_uri.setDataSource(working_copy_schema, new_uri.table()+"_view", new_uri.geometryColumn(), new_uri.sql(), new_uri.keyColumn()) display_name = QgsMapLayerRegistry.instance().mapLayer(layer_id).name() print "replacing ", display_name src = new_uri.uri().replace('()','') new_layer = self.iface.addVectorLayer(src, display_name, 'postgres') self.iface.legendInterface().moveLayer( new_layer, grp_idx)
def addButtons(self): buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self) self.ok_button = buttons.button(QDialogButtonBox.Ok) self.ok_button.setEnabled(False) self.layout.addRow(self.createSpace(10)) self.layout.addRow(buttons) self.connect(buttons, SIGNAL('accepted()'), self.accept) self.connect(buttons, SIGNAL('rejected()'), self.reject)
class DeletionOptions(QDialog): def __init__(self, parent, model): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint QDialog.__init__(self, parent, flags) self.model = model self._setupUi() self.model.view = self self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) def _setupUi(self): self.setWindowTitle(tr("Deletion Options")) self.resize(400, 270) self.verticalLayout = QVBoxLayout(self) self.msgLabel = QLabel() self.verticalLayout.addWidget(self.msgLabel) self.linkCheckbox = QCheckBox(tr("Link deleted files")) self.verticalLayout.addWidget(self.linkCheckbox) text = tr("After having deleted a duplicate, place a link targeting the reference file " "to replace the deleted file.") self.linkMessageLabel = QLabel(text) self.linkMessageLabel.setWordWrap(True) self.verticalLayout.addWidget(self.linkMessageLabel) self.linkTypeRadio = RadioBox(items=[tr("Symlink"), tr("Hardlink")], spread=False) self.verticalLayout.addWidget(self.linkTypeRadio) if not self.model.supports_links(): self.linkCheckbox.setEnabled(False) self.linkTypeRadio.setEnabled(False) self.linkCheckbox.setText(self.linkCheckbox.text() + tr(" (unsupported)")) self.directCheckbox = QCheckBox(tr("Directly delete files")) self.verticalLayout.addWidget(self.directCheckbox) text = tr("Instead of sending files to trash, delete them directly. This option is usually " "used as a workaround when the normal deletion method doesn't work.") self.directMessageLabel = QLabel(text) self.directMessageLabel.setWordWrap(True) self.verticalLayout.addWidget(self.directMessageLabel) self.buttonBox = QDialogButtonBox() self.buttonBox.addButton(tr("Proceed"), QDialogButtonBox.AcceptRole) self.buttonBox.addButton(tr("Cancel"), QDialogButtonBox.RejectRole) self.verticalLayout.addWidget(self.buttonBox) #--- model --> view def update_msg(self, msg): self.msgLabel.setText(msg) def show(self): self.linkCheckbox.setChecked(self.model.link_deleted) self.linkTypeRadio.selected_index = 1 if self.model.use_hardlinks else 0 self.directCheckbox.setChecked(self.model.direct) result = self.exec() self.model.link_deleted = self.linkCheckbox.isChecked() self.model.use_hardlinks = self.linkTypeRadio.selected_index == 1 self.model.direct = self.directCheckbox.isChecked() return result == QDialog.Accepted
def initUI(self): u"""Build the dialog box.""" self.setWindowTitle(_(u'Anki – Download audio')) self.setWindowIcon(QIcon(":/icons/anki.png")) layout = QGridLayout() self.setLayout(layout) explanation = QLabel(self) if len(self.list) > 1: explanation.setText( _(u'Please select an action for each downloaded file:')) else: explanation.setText(_(u'Please select what to do with the file:')) layout.addWidget(explanation, 0, 0, 1, self.num_columns) if not self.hide_text: text_head_label = QLabel(_(u'<b>Source text</b>'), self) layout.addWidget(text_head_label, 1, 0, 1, 2) text_head_label.setToolTip(self.text_help) else: text_head_label = QLabel(_(u'<b>Source</b>'), self) layout.addWidget(text_head_label, 1, 0) text_head_label.setToolTip(self.text_hide_help) play_head_label = QLabel(_(u'play'), self) play_head_label.setToolTip(self.play_help) layout.addWidget(play_head_label, 1, self.play_column) play_old_head_label = QLabel(_(u'play old'), self) if not self.hide_text: play_old_head_label.setToolTip(self.play_old_help) else: play_old_head_label.setToolTip(self.play_old_hide_help) layout.addWidget(play_old_head_label, 1, self.play_old_column) add_head_label = QLabel(_(u'add'), self) add_head_label.setToolTip(self.add_help_text_long) layout.addWidget(add_head_label, 1, self.add_column) keep_head_label = QLabel(_(u'keep'), self) keep_head_label.setToolTip(self.keep_help_text_long) layout.addWidget(keep_head_label, 1, self.keep_column) delete_head_label = QLabel(_(u'delete'), self) delete_head_label.setToolTip(self.delete_help_text_long) layout.addWidget(delete_head_label, 1, self.delete_column) if self.show_skull_and_bones: blacklist_head_label = QLabel(_(u'blacklist'), self) blacklist_head_label.setToolTip(self.blacklist_help_text_long) layout.addWidget(blacklist_head_label, 1, self.blacklist_column) rule_label = QLabel('<hr>') layout.addWidget(rule_label, 2, 0, 1, self.num_columns) self.create_rows(layout) dialog_buttons = QDialogButtonBox(self) dialog_buttons.addButton(QDialogButtonBox.Cancel) dialog_buttons.addButton(QDialogButtonBox.Ok) self.connect(dialog_buttons, SIGNAL("accepted()"), self, SLOT("accept()")) self.connect(dialog_buttons, SIGNAL("rejected()"), self, SLOT("reject()")) layout.addWidget(dialog_buttons, len(self.buttons_groups) + 3, 0, 1, self.num_columns)
class LineEditDialog(QDialog): """ A dialog asking for page/file name. It also checks for name crash. """ def __init__(self, path, parent=None): super(LineEditDialog, self).__init__(parent) self.path = path # newPage/newSubpage if parent.objectName() in ["mikiWindow", "notesTree"]: editorLabel = QLabel("Page Name:") self.extNames = [".md", ".markdown", ".mkd"] # Copy Image to notesEdit elif parent.objectName() == "notesEdit": editorLabel = QLabel("File Name:") self.extNames = ["", ".jpg"] else: return self.editor = QLineEdit() editorLabel.setBuddy(self.editor) self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False) layout = QGridLayout() layout.addWidget(editorLabel, 0, 0) layout.addWidget(self.editor, 0, 1) layout.addWidget(self.buttonBox, 1, 1) self.setLayout(layout) self.editor.textEdited.connect(self.updateUi) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) def setText(self, text): self.editor.setText(text) self.editor.selectAll() def updateUi(self): self.buttonBox.button(QDialogButtonBox.Ok).setEnabled( self.editor.text() != "") def accept(self): notePath = os.path.join(self.path, self.editor.text()) acceptable = True for ext in self.extNames: if QFile.exists(notePath + ext): acceptable = False QMessageBox.warning(self, 'Error', 'File already exists: %s' % notePath + ext) break if acceptable: QDialog.accept(self)
class RepoRemoveDialog(QDialog): def __init__(self, github, name, parent=None): super(RepoRemoveDialog, self).__init__( parent, windowTitle="Remove Repo") self.github = github self.login = self.github.get_user().login self.name = name self.label = QLabel(''' <p>Are you sure?</p> <p>This action <b>CANNOT</b> be undone.</p> <p>This will delete the <b>{}/{}</b> repository, wiki, issues, and comments permanently.</p> <p>Please type in the name of the repository to confirm.</p> '''.format(self.login, self.name)) self.label.setTextFormat(Qt.RichText) validator = QRegExpValidator( QRegExp(r'{}/{}'.format(self.login, self.name))) self.nameEdit = QLineEdit(textChanged=self.textChanged) self.nameEdit.setValidator(validator) # Form self.form = QFormLayout() self.form.addRow(self.label) self.form.addRow(self.nameEdit) # ButtonBox self.buttonBox = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel, accepted=self.accept, rejected=self.reject) # Layout self.mainLayout = QVBoxLayout() self.mainLayout.addLayout(self.form) self.mainLayout.addWidget(self.buttonBox) self.setLayout(self.mainLayout) self.textChanged() def textChanged(self): if self.nameEdit.validator().validate(self.nameEdit.text(), 0)[0] \ == QValidator.Acceptable: b = True else: b = False self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(b)
def add_button_box(self, stdbtns): """Create dialog button box and add it to the dialog layout""" bbox = QDialogButtonBox(stdbtns) run_btn = bbox.addButton(_("Run"), QDialogButtonBox.AcceptRole) self.connect(run_btn, SIGNAL('clicked()'), self.run_btn_clicked) self.connect(bbox, SIGNAL("accepted()"), SLOT("accept()")) self.connect(bbox, SIGNAL("rejected()"), SLOT("reject()")) btnlayout = QHBoxLayout() btnlayout.addStretch(1) btnlayout.addWidget(bbox) self.layout().addLayout(btnlayout)
def __init__(self, title = "Title", description = "Description", unique_names = None, choose_from_list=False): QDialog.__init__(self) self.setModal(True) self.setWindowTitle(title) # self.setMinimumWidth(250) # self.setMinimumHeight(150) if unique_names is None: unique_names = [] self.unique_names = unique_names self.choose_from_list = choose_from_list self.layout = QFormLayout() self.layout.setSizeConstraint(QLayout.SetFixedSize) label = QLabel(description) label.setAlignment(Qt.AlignHCenter) self.layout.addRow(self.createSpace(5)) self.layout.addRow(label) self.layout.addRow(self.createSpace(10)) buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self) self.ok_button = buttons.button(QDialogButtonBox.Ok) self.ok_button.setEnabled(False) if choose_from_list: self.param_name_combo = QComboBox() self.connect(self.param_name_combo, SIGNAL('currentIndexChanged(QString)'), self.validateChoice) for item in unique_names: self.param_name_combo.addItem(item) self.layout.addRow("Job:", self.param_name_combo) else: self.param_name = QLineEdit(self) self.param_name.setFocus() self.connect(self.param_name, SIGNAL('textChanged(QString)'), self.validateName) self.validColor = self.param_name.palette().color(self.param_name.backgroundRole()) self.layout.addRow("Name:", self.param_name) self.layout.addRow(self.createSpace(10)) self.layout.addRow(buttons) self.connect(buttons, SIGNAL('accepted()'), self.accept) self.connect(buttons, SIGNAL('rejected()'), self.reject) self.setLayout(self.layout)
class DlgAixmSelectPosition(QDialog): def __init__(self, parent=None): QDialog.__init__(self, parent) self.resize(290, 136) self.setWindowTitle("New DPN DB Entry") 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) self.groupBox.Caption = "Existing DB Entries" verticalLayoutDlg.addWidget(self.groupBox) self.lstItems = ListBox(self.groupBox) self.groupBox.Add = self.lstItems frame = Frame(self, "HL") verticalLayoutDlg.addWidget(frame) self.btnNewDPN = QPushButton(frame) self.btnNewDPN.setObjectName("btnNewDPN") self.btnNewDPN.setText("New DPN...") frame.Add = self.btnNewDPN self.btnNewPCP = QPushButton(frame) self.btnNewPCP.setObjectName("btnNewPCP") self.btnNewPCP.setText("New PCP...") frame.Add = self.btnNewPCP self.btnBoxOkCancel = QDialogButtonBox(frame) self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel")) self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg) self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject) self.btnNewDPN.clicked.connect(self.btnNewDPN_Click) self.btnNewPCP.clicked.connect(self.btnNewPCP_Click) frame.Add = self.btnBoxOkCancel self.newTypeSelected = None def acceptDlg(self): self.accept() def btnNewDPN_Click(self): self.newTypeSelected = NewDbEntryType.DPN self.reject() def btnNewPCP_Click(self): self.newTypeSelected = NewDbEntryType.PCP self.reject() @staticmethod def resultPointValueListMethod(resultValueList, dataBaseProcedureData_0, point3d_0, procEntityListType_0, parent): if len(resultValueList) > 0: lat = None lon = None if define._units == QGis.Meters: point3d = QgisHelper.CrsTransformPoint( float(resultValueList[1]), float(resultValueList[2]), define._xyCrs, define._latLonCrs) lat = Degrees(point3d.get_Y(), None, None, DegreesType.Latitude) lon = Degrees(point3d.get_X(), None, None, DegreesType.Longitude) else: lat = Degrees(float(resultValueList[2]), None, None, DegreesType.Latitude) lon = Degrees(float(resultValueList[1]), None, None, DegreesType.Longitude) str0 = lon.method_1("dddmmss.ssssH") textString = lat.method_1("ddmmss.ssssH") procEntityBases = DlgAixmSelectPosition.smethod_1( dataBaseProcedureData_0, procEntityListType_0, point3d_0, textString, str0) dlgAixmSelectPosition = DlgAixmSelectPosition() naN = None degree = None result, naN, degree = Geo.smethod_2(point3d_0.get_X(), point3d_0.get_Y()) if (result): dataBaseProcedureData_0.method_60(procEntityBases, procEntityListType_0, naN.ToString(), degree.ToString()) dlgAixmSelectPosition.lstItems.Sorted = True for procEntityBase in procEntityBases: dlgAixmSelectPosition.lstItems.Add(procEntityBase) if (procEntityListType_0 != ProcEntityListType.CentersEx and procEntityListType_0 != ProcEntityListType.FixesEx): dlgAixmSelectPosition.btnNewPCP.setEnabled(False) dlgAixmSelectPosition.btnNewPCP.setVisible(False) resultDlg = dlgAixmSelectPosition.exec_() procEntityBase_0 = None if (resultDlg != 1): if dlgAixmSelectPosition.newTypeSelected == NewDbEntryType.DPN: flag, procEntityBase_0 = DlgAixmNewDPN.smethod_0( dataBaseProcedureData_0, naN, degree) elif dlgAixmSelectPosition.newTypeSelected == NewDbEntryType.PCP: flag, procEntityBase_0 = DlgAixmNewPCP.smethod_0( dataBaseProcedureData_0, naN, degree) else: flag = False else: procEntityBase_0 = dlgAixmSelectPosition.lstItems.SelectedItem flag = True QObject.emit(parent, SIGNAL("DlgAixmSelectPosition_Smethod_0_Event"), flag, procEntityBase_0) return @staticmethod #### complete def smethod_0(dataBaseProcedureData_0, point3d_0, procEntityListType_0): flag = False procEntityBase_0 = None CaptureCoordTool = CaptureCoordinateToolUpdate( define._canvas, dataBaseProcedureData_0, point3d_0, procEntityListType_0) define._canvas.setMapTool(CaptureCoordTool) QObject.connect(CaptureCoordTool, SIGNAL("resultPointValueList"), DlgAixmSelectPosition.resultPointValueListMethod) return CaptureCoordTool @staticmethod def smethod_1(dataBaseProcedureData_0, procEntityListType_0, point3d_0, textString, strS): procEntityBases = [] for case in switch(procEntityListType_0): if case(ProcEntityListType.Holding) or case( ProcEntityListType.Fixes) or case( ProcEntityListType.FixesEx) or case( ProcEntityListType.Centers) or case( ProcEntityListType.CentersEx): if (not String.IsNullOrEmpty(textString) and not String.IsNullOrEmpty(strS)): dataBaseProcedureData_0.method_60(procEntityBases, procEntityListType_0, textString, strS) return procEntityBases else: return None return None
def createDialog(self): """ Create qt dialog """ self.buttonBox = QDialogButtonBox(self) self.buttonBox.setStyleSheet("""QDialogButtonBox { dialogbuttonbox-buttons-have-icons: 1; dialog-ok-icon: url(:/ok.png); dialog-cancel-icon: url(:/test-close-black.png); }""") self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) mainLayout = QHBoxLayout() main2Layout = QHBoxLayout() titleLabel = QLabel(self.currentOperator['operator']) font = QFont() font.setBold(True) titleLabel.setFont(font) self.opType = QComboBox() if not self.liteMode: for i in xrange(len(LIST_CONDITIONS)): self.opType.addItem(LIST_CONDITIONS[i].title()) if self.currentOperator['operator'] == LIST_CONDITIONS[ i].title(): self.opType.setCurrentIndex(i) else: for i in xrange(len(LIST_CONDITIONS_LITE)): self.opType.addItem(LIST_CONDITIONS_LITE[i].title()) if self.currentOperator['operator'] == LIST_CONDITIONS_LITE[ i].title(): self.opType.setCurrentIndex(i) main2Layout.addWidget(titleLabel) main2Layout.addWidget(self.opType) if not self.liteMode: self.textValue = QTextEdit() self.textValue.setFixedHeight(HEIGHT_TEXT_AREA) self.textValue.setMinimumWidth(WIDTH_TEXT_AREA) radioGroup = QButtonGroup(self) self.strRadioButton = QRadioButton("string") self.strRadioButton.setChecked(True) self.inRadioButton = QRadioButton("inputs") self.outRadioButton = QRadioButton("outputs") self.varRadioButton = QRadioButton("variables") radioGroup.addButton(self.strRadioButton) radioGroup.addButton(self.inRadioButton) radioGroup.addButton(self.outRadioButton) radioGroup.addButton(self.varRadioButton) self.inputsCombo = QComboBox() for inpt in self.parentWidget.getInputs(): self.inputsCombo.addItem(inpt['name']) self.outputsCombo = QComboBox() for inpt in self.parentWidget.getOutputs(): self.outputsCombo.addItem(inpt['name']) self.variablesCombo = QComboBox() self.variablesCombo.addItems(self.parentWidget.variables) if self.currentOperator['type'] == 'string': self.strRadioButton.setChecked(True) self.textValue.setText(self.currentOperator['value']) if self.currentOperator['type'] == 'inputs': self.inRadioButton.setChecked(True) for x in xrange(self.inputsCombo.count()): if self.inputsCombo.itemText( x) == self.currentOperator['value']: self.inputsCombo.setCurrentIndex(x) if self.currentOperator['type'] == 'outputs': self.outRadioButton.setChecked(True) for x in xrange(self.outputsCombo.count()): if self.outputsCombo.itemText( x) == self.currentOperator['value']: self.outputsCombo.setCurrentIndex(x) if self.currentOperator['type'] == 'variables': self.varRadioButton.setChecked(True) for x in xrange(self.variablesCombo.count()): if self.variablesCombo.itemText( x) == self.currentOperator['value']: self.variablesCombo.setCurrentIndex(x) mainLayout.addWidget(self.strRadioButton) mainLayout.addWidget(self.textValue) mainLayout.addWidget(self.inRadioButton) mainLayout.addWidget(self.inputsCombo) mainLayout.addWidget(self.outRadioButton) mainLayout.addWidget(self.outputsCombo) mainLayout.addWidget(self.varRadioButton) mainLayout.addWidget(self.variablesCombo) finalLayout = QVBoxLayout() finalLayout.addLayout(main2Layout) finalLayout.addLayout(mainLayout) finalLayout.addWidget(self.buttonBox) self.setLayout(finalLayout) self.setWindowTitle(self.tr("Operators configuration")) self.setMinimumWidth(500) self.center()
def __init__(self, mainwindow): super(Dialog, self).__init__(mainwindow) self._document = None layout = QGridLayout() self.setLayout(layout) self.versionLabel = QLabel() self.lilyChooser = lilychooser.LilyChooser() self.outputLabel = QLabel() self.outputCombo = QComboBox() self.resolutionLabel = QLabel() self.resolutionCombo = QComboBox(editable=True) self.antialiasLabel = QLabel() self.antialiasSpin = QSpinBox(minimum=1, maximum=128, value=1) self.modeLabel = QLabel() self.modeCombo = QComboBox() self.englishCheck = QCheckBox() self.deleteCheck = QCheckBox() self.commandLineLabel = QLabel() self.commandLine = QTextEdit(acceptRichText=False) self.buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttons.button(QDialogButtonBox.Ok).setIcon( icons.get("lilypond-run")) userguide.addButton(self.buttons, "engrave_custom") self.resolutionCombo.addItems(['100', '200', '300', '600', '1200']) self.resolutionCombo.setCurrentIndex(2) self.modeCombo.addItems(['preview', 'publish', 'debug']) layout.addWidget(self.versionLabel, 0, 0) layout.addWidget(self.lilyChooser, 0, 1, 1, 3) layout.addWidget(self.outputLabel, 1, 0) layout.addWidget(self.outputCombo, 1, 1, 1, 3) layout.addWidget(self.resolutionLabel, 2, 0) layout.addWidget(self.resolutionCombo, 2, 1) layout.addWidget(self.antialiasLabel, 2, 2, Qt.AlignRight) layout.addWidget(self.antialiasSpin, 2, 3) layout.addWidget(self.modeLabel, 3, 0) layout.addWidget(self.modeCombo, 3, 1, 1, 3) layout.addWidget(self.englishCheck, 4, 0, 1, 4) layout.addWidget(self.deleteCheck, 5, 0, 1, 4) layout.addWidget(self.commandLineLabel, 6, 0, 1, 4) layout.addWidget(self.commandLine, 7, 0, 1, 4) layout.addWidget(widgets.Separator(), 8, 0, 1, 4) layout.addWidget(self.buttons, 9, 0, 1, 4) app.translateUI(self) qutil.saveDialogSize(self, "engrave/custom/dialog/size", QSize(480, 260)) self.buttons.accepted.connect(self.accept) self.buttons.rejected.connect(self.reject) model = listmodel.ListModel(formats, display=lambda f: f.title(), icon=lambda f: icons.file_type(f.type)) self.outputCombo.setModel(model) s = QSettings() s.beginGroup("lilypond_settings") self.englishCheck.setChecked(s.value("no_translation", False, bool)) self.deleteCheck.setChecked( s.value("delete_intermediate_files", True, bool)) if s.value("default_output_target", "pdf", type("")) == "svg": self.outputCombo.setCurrentIndex(3) app.jobFinished.connect(self.slotJobFinished) self.outputCombo.currentIndexChanged.connect(self.makeCommandLine) self.modeCombo.currentIndexChanged.connect(self.makeCommandLine) self.deleteCheck.toggled.connect(self.makeCommandLine) self.resolutionCombo.editTextChanged.connect(self.makeCommandLine) self.antialiasSpin.valueChanged.connect(self.makeCommandLine) self.makeCommandLine() panelmanager.manager( mainwindow).layoutcontrol.widget().optionsChanged.connect( self.makeCommandLine)
class GPFModelerParameterDefinitionDialog(ModelerParameterDefinitionDialog): PARAMETER_BANDS = "Raster bands" paramTypes = ModelerParameterDefinitionDialog.paramTypes if PARAMETER_BANDS not in paramTypes: paramTypes.extend([PARAMETER_BANDS]) def setupUi(self): if self.paramType == GPFModelerParameterDefinitionDialog.PARAMETER_BANDS or \ isinstance(self.param, ParameterBands): self.setWindowTitle(self.tr('Parameter definition')) self.verticalLayout = QVBoxLayout(self) self.verticalLayout.setSpacing(40) self.verticalLayout.setMargin(20) self.horizontalLayoutName = QHBoxLayout(self) self.horizontalLayoutName.setSpacing(2) self.horizontalLayoutName.setMargin(0) self.label = QLabel(self.tr('Parameter name')) self.horizontalLayoutName.addWidget(self.label) self.nameTextBox = QLineEdit() self.horizontalLayoutName.addWidget(self.nameTextBox) self.verticalLayout.addLayout(self.horizontalLayoutName) self.horizontalLayoutRequired = QHBoxLayout(self) self.horizontalLayoutRequired.setSpacing(2) self.horizontalLayoutRequired.setMargin(0) self.horizontalLayoutParent = QHBoxLayout(self) self.horizontalLayoutParent.setSpacing(2) self.horizontalLayoutParent.setMargin(0) self.horizontalLayoutDefault = QHBoxLayout(self) self.horizontalLayoutDefault.setSpacing(2) self.horizontalLayoutDefault.setMargin(0) self.horizontalLayoutDatatype = QHBoxLayout(self) self.horizontalLayoutDatatype.setSpacing(2) self.horizontalLayoutDatatype.setMargin(0) if isinstance(self.param, Parameter): self.nameTextBox.setText(self.param.description) self.horizontalLayoutDefault.addWidget(QLabel(self.tr('Default band'))) self.defaultTextBox = QLineEdit() if self.param is not None: self.defaultTextBox.setText(self.param.default) self.horizontalLayoutDefault.addWidget(self.defaultTextBox) self.verticalLayout.addLayout(self.horizontalLayoutDefault) self.horizontalLayoutDefault.addWidget(QLabel(self.tr('Raster layer'))) self.parentCombo = QComboBox() idx = 0 for param in self.alg.inputs.values(): if isinstance(param.param, (ParameterRaster)): self.parentCombo.addItem(param.param.description, param.param.name) if self.param is not None: if self.param.bandSourceRaster == param.param.name: self.parentCombo.setCurrentIndex(idx) idx += 1 self.horizontalLayoutDefault.addWidget(self.parentCombo) self.verticalLayout.addLayout(self.horizontalLayoutDefault) self.horizontalLayoutRequired.addWidget(QLabel(self.tr('Required'))) self.yesNoCombo = QComboBox() self.yesNoCombo.addItem(self.tr('Yes')) self.yesNoCombo.addItem(self.tr('No')) self.horizontalLayoutRequired.addWidget(self.yesNoCombo) if self.param is not None: self.yesNoCombo.setCurrentIndex( 1 if self.param.optional else 0) self.verticalLayout.addLayout(self.horizontalLayoutRequired) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.buttonBox.setObjectName('buttonBox') self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) self.verticalLayout.addWidget(self.buttonBox) self.setLayout(self.verticalLayout) else: ModelerParameterDefinitionDialog.setupUi(self) def okPressed(self): if self.paramType == GPFModelerParameterDefinitionDialog.PARAMETER_BANDS or \ isinstance(self.param, ParameterBands): description = unicode(self.nameTextBox.text()) if description.strip() == '': QMessageBox.warning(self, self.tr('Unable to define parameter'), self.tr('Invalid parameter name')) return if self.param is None: validChars = \ 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' safeName = ''.join(c for c in description if c in validChars) name = safeName.lower() i = 2 while name in self.alg.inputs: name = safeName.lower() + str(i) else: name = self.param.name if self.parentCombo.currentIndex() < 0: QMessageBox.warning(self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return raster = self.parentCombo.itemData(self.parentCombo.currentIndex()) default = unicode(self.defaultTextBox.text()) self.param = ParameterBands(name, description, default, raster, optional=False) self.param.optional = self.yesNoCombo.currentIndex() == 1 self.close() else: ModelerParameterDefinitionDialog.okPressed(self)
def setupUi(self): self.setWindowTitle('Edit filter') #self.resize(400, 300) self.signatureLabel = QLabel(self) self.signatureLabel.setText('def filter(block):') font = QFont('Some font that does not exist') font.setStyleHint(font.TypeWriter, font.PreferDefault) self.editor = CodeEditor(self) self.editor.setup_editor(linenumbers=False, language='py', scrollflagarea=False, codecompletion_enter=True, font=font, highlight_current_line=False, occurence_highlighting=False) self.editor.setCursor(Qt.IBeamCursor) self.editor.horizontalScrollBar().setCursor(Qt.ArrowCursor) self.editor.verticalScrollBar().setCursor(Qt.ArrowCursor) self.editor.set_text('return True') self.onExceptionCheckBox = QCheckBox(self) self.onExceptionCheckBox.setText('True on exception') self.onExceptionCheckBox.setToolTip('Determines if the filter will ' 'admit items if there is an ' 'exception during its execution') self.combinedCheckBox = QCheckBox(self) self.combinedCheckBox.setText('Combined filter') self.combinedCheckBox.setToolTip('Determines if the filter operates ' 'on single items (return True or ' 'False) or lists of items (return a ' 'list of items to be admitted)') self.filterTypeComboBox = QComboBox(self) self.filterTypeComboBox.addItem('Block') self.filterTypeComboBox.addItem('Segment') self.filterTypeComboBox.addItem('Recording Channel Group') self.filterTypeComboBox.addItem('Recording Channel') self.filterTypeComboBox.addItem('Unit') self.filterGroupComboBox = QComboBox(self) self.nameLineEdit = QLineEdit() self.dialogButtonBox = QDialogButtonBox(self) self.dialogButtonBox.setAutoFillBackground(False) self.dialogButtonBox.setOrientation(Qt.Horizontal) self.dialogButtonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.dialogButtonBox.setCenterButtons(True) gridLayout = QGridLayout(self) gridLayout.addWidget(self.signatureLabel, 0, 0, 1, 4) gridLayout.addWidget(self.editor, 1, 0, 1, 4) gridLayout.addWidget(self.onExceptionCheckBox, 2, 2, 1, 1) gridLayout.addWidget(self.combinedCheckBox, 2, 3, 1, 1) gridLayout.addWidget(QLabel('Type:', self), 2, 0) gridLayout.addWidget(self.filterTypeComboBox, 2, 1) gridLayout.addWidget(QLabel('Group:', self), 3, 0) gridLayout.addWidget(self.filterGroupComboBox, 3, 1, 1, 3) gridLayout.addWidget(QLabel('Name:', self), 4, 0) gridLayout.addWidget(self.nameLineEdit, 4, 1, 1, 3) gridLayout.addWidget(self.dialogButtonBox, 5, 0, 1, 4) self.connect(self.dialogButtonBox, SIGNAL('accepted()'), self.accept) self.connect(self.dialogButtonBox, SIGNAL('rejected()'), self.reject) self.combinedCheckBox.stateChanged.connect(self.combined_state_changed) self.connect(self.filterTypeComboBox, SIGNAL('currentIndexChanged(int)'), self.on_filterTypeComboBox_currentIndexChanged)
def __init__(self, parent=None, buttons=None): super(XPopupWidget, self).__init__(parent) # define custom properties self._anchor = XPopupWidget.Anchor.TopCenter self._autoCalculateAnchor = False self._autoCloseOnAccept = True self._autoCloseOnReject = True self._autoCloseOnFocusOut = False self._autoDefault = True self._first = True self._animated = False self._currentMode = None self._positionLinkedTo = [] # define controls self._resizable = True self._popupPadding = 10 self._titleBarVisible = True self._buttonBoxVisible = True self._dialogButton = QToolButton(self) self._closeButton = QToolButton(self) self._scrollArea = QScrollArea(self) self._sizeGrip = QSizeGrip(self) self._sizeGrip.setFixedWidth(12) self._sizeGrip.setFixedHeight(12) self._leftSizeGrip = QSizeGrip(self) self._leftSizeGrip.setFixedWidth(12) self._leftSizeGrip.setFixedHeight(12) if buttons is None: buttons = QDialogButtonBox.NoButton self._buttonBox = QDialogButtonBox(buttons, Qt.Horizontal, self) self._buttonBox.setContentsMargins(3, 0, 3, 9) self._scrollArea.setWidgetResizable(True) self._scrollArea.setFrameShape(QScrollArea.NoFrame) self._scrollArea.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) palette = self.palette() self._scrollArea.setPalette(palette) self._dialogButton.setToolTip('Popout to Dialog') self._closeButton.setToolTip('Close Popup') for btn in (self._dialogButton, self._closeButton): btn.setAutoRaise(True) btn.setIconSize(QSize(14, 14)) btn.setMaximumSize(16, 16) # setup the icons icon = QIcon(projexui.resources.find('img/dialog.png')) self._dialogButton.setIcon(icon) icon = QIcon(projexui.resources.find('img/close.png')) self._closeButton.setIcon(icon) # define the ui hlayout = QHBoxLayout() hlayout.setSpacing(0) hlayout.addStretch(1) hlayout.addWidget(self._dialogButton) hlayout.addWidget(self._closeButton) hlayout.setContentsMargins(0, 0, 0, 0) hlayout2 = QHBoxLayout() hlayout2.addWidget(self._buttonBox) hlayout2.setContentsMargins(0, 0, 3, 0) vlayout = QVBoxLayout() vlayout.addLayout(hlayout) vlayout.addWidget(self._scrollArea) vlayout.addLayout(hlayout2) vlayout.setContentsMargins(3, 2, 3, 2) vlayout.setSpacing(0) self.setLayout(vlayout) self.setPositionLinkedTo(parent) # set default properties self.setAutoFillBackground(True) self.setBackgroundRole(QPalette.Button) self.setWindowTitle('Popup') self.setFocusPolicy(Qt.StrongFocus) self.setCurrentMode(XPopupWidget.Mode.Popup) # create connections self._dialogButton.clicked.connect(self.setDialogMode) self._closeButton.clicked.connect(self.reject) self._buttonBox.accepted.connect(self.accept) self._buttonBox.rejected.connect(self.reject) self._buttonBox.clicked.connect(self.handleButtonClick)
class UI_Psychrometry(QDialog): """Psychrometric charts tool""" def __init__(self, parent=None): super(UI_Psychrometry, self).__init__(parent) self.showMaximized() self.setWindowTitle("Psychrometric chart") layout = QGridLayout(self) self.diagrama2D = PsychroPlot(self, dpi=90) self.diagrama2D.fig.canvas.mpl_connect('motion_notify_event', self.scroll) layout.addWidget(self.diagrama2D, 1, 1, 1, 2) self.progressBar = QProgressBar() self.progressBar.setVisible(False) layout.addWidget(self.progressBar, 2, 1) self.status = QLabel() layout.addWidget(self.status, 2, 1) self.buttonBox = QDialogButtonBox(QDialogButtonBox.Close) butonPNG = QPushButton("Save as PNG") self.buttonBox.addButton(butonPNG, QDialogButtonBox.AcceptRole) self.buttonBox.rejected.connect(self.reject) self.buttonBox.accepted.connect(self.savePNG) layout.addWidget(self.buttonBox, 2, 2) self.plot() def savePNG(self): """Save chart image to png file""" fname = unicode(QFileDialog.getSaveFileName( self, "Save chart to file", "./", "Portable Network Graphics (*.png)")) self.diagrama2D.fig.savefig(fname, facecolor='#eeeeee') def drawlabel(self, name, Preferences, t, W, label, unit): """ Draw annotation for isolines name: name of isoline Preferences: Configparse instance of pychemqt preferences t: x array of line W: y array of line label: text value to draw unit: text units to draw """ if Preferences.getboolean("Psychr", name+"label"): tmin = Preferences.getfloat("Psychr", "isotdbStart")-273.15 tmax = Preferences.getfloat("Psychr", "isotdbEnd")-273.15 x = tmax-tmin wmin = Preferences.getfloat("Psychr", "isowStart") wmax = Preferences.getfloat("Psychr", "isowEnd") y = wmax-wmin i = 0 for ti, wi in zip(t, W): if tmin <= ti <= tmax and wmin <= wi <= wmax: i += 1 label = str(label) if Preferences.getboolean("Psychr", name+"units"): label += unit pos = Preferences.getfloat("Psychr", name+"position") p = int(i*pos/100-1) rot = np.arctan((W[p]-W[p-1])/y/(t[p]-t[p-1])*x)*360.0/2.0/np.pi self.diagrama2D.axes2D.annotate(label, (t[p], W[p]), rotation=rot, size="small", ha="center", va="center") def plot(self): """Plot chart""" Preferences = ConfigParser() Preferences.read("psyrc") self.diagrama2D.axes2D.clear() self.diagrama2D.config() filename = "%i.pkl" % P if os.path.isfile(filename): with open(filename, "r") as archivo: data = cPickle.load(archivo) self.status.setText("Loading cached data...") QApplication.processEvents() else: self.progressBar.setVisible(True) self.status.setText("Calculating data, be patient...") QApplication.processEvents() data = PsyCoolprop.calculatePlot(self) cPickle.dump(data, open(filename, "w")) self.progressBar.setVisible(False) self.status.setText("Plotting...") QApplication.processEvents() tmax = Preferences.getfloat("Psychr", "isotdbEnd")-273.15 t = [ti-273.15 for ti in data["t"]] Hs = data["Hs"] format = {} format["ls"] = Preferences.get("Psychr", "saturationlineStyle") format["lw"] = Preferences.getfloat("Psychr", "saturationlineWidth") format["color"] = Preferences.get("Psychr", "saturationColor") format["marker"] = Preferences.get("Psychr", "saturationmarker") format["markersize"] = 3 self.diagrama2D.plot(t, Hs, **format) format = {} format["ls"] = Preferences.get("Psychr", "isotdblineStyle") format["lw"] = Preferences.getfloat("Psychr", "isotdblineWidth") format["color"] = Preferences.get("Psychr", "isotdbColor") format["marker"] = Preferences.get("Psychr", "isotdbmarker") format["markersize"] = 3 for i, T in enumerate(t): self.diagrama2D.plot([T, T], [0, Hs[i]], **format) H = data["H"] th = data["th"] format = {} format["ls"] = Preferences.get("Psychr", "isowlineStyle") format["lw"] = Preferences.getfloat("Psychr", "isowlineWidth") format["color"] = Preferences.get("Psychr", "isowColor") format["marker"] = Preferences.get("Psychr", "isowmarker") format["markersize"] = 3 for i, H in enumerate(H): self.diagrama2D.plot([th[i], tmax], [H, H], **format) format = {} format["ls"] = Preferences.get("Psychr", "isohrlineStyle") format["lw"] = Preferences.getfloat("Psychr", "isohrlineWidth") format["color"] = Preferences.get("Psychr", "isohrColor") format["marker"] = Preferences.get("Psychr", "isohrmarker") format["markersize"] = 3 for Hr, H0 in data["Hr"].iteritems(): self.diagrama2D.plot(t, H0, **format) self.drawlabel("isohr", Preferences, t, H0, Hr, "%") format = {} format["ls"] = Preferences.get("Psychr", "isotwblineStyle") format["lw"] = Preferences.getfloat("Psychr", "isotwblineWidth") format["color"] = Preferences.get("Psychr", "isotwbColor") format["marker"] = Preferences.get("Psychr", "isotwbmarker") format["markersize"] = 3 for T, (H, Tw) in data["Twb"].iteritems(): self.diagrama2D.plot(Tw, H, **format) value = T-273.15 txt = u"ºC" self.drawlabel("isotwb", Preferences, Tw, H, value, txt) format = {} format["ls"] = Preferences.get("Psychr", "isochorlineStyle") format["lw"] = Preferences.getfloat("Psychr", "isochorlineWidth") format["color"] = Preferences.get("Psychr", "isochorColor") format["marker"] = Preferences.get("Psychr", "isochormarker") format["markersize"] = 3 for v, (Td, H) in data["v"].iteritems(): self.diagrama2D.plot(Td, H, **format) value = v txt = u"m³/kg" self.drawlabel("isochor", Preferences, Td, H, value, txt) self.diagrama2D.draw() self.status.setText("P = %i Pa" % P) def scroll(self, event): """Update graph annotate when mouse scroll over chart""" if event.xdata and event.ydata: punto = self.createState(event.xdata, event.ydata) if event.ydata < punto.ws: self.diagrama2D.showPointData(punto) else: self.diagrama2D.clearPointData() def createState(self, x, y): """Create psychrometric state from click or mouse position""" tdb = x+273.15 punto = PsyCoolprop(P=P, tdb=tdb, w=y) return punto
def setup_and_check(self, data, title='', xy=False, readonly=False): """ Setup ArrayEditor: return False if data is not supported, True otherwise """ self.arraywidget = None self.is_record_array = data.dtype.names is not None if len(data.shape) > 2: self.error( self.tr("Arrays with more than 2 dimensions " "are not supported")) return False if not self.is_record_array: dtn = data.dtype.name if dtn not in SUPPORTED_FORMATS and not dtn.startswith('string') \ and not dtn.startswith('unicode'): arr = self.tr("%1 arrays").arg(data.dtype.name) self.error(self.tr("%1 are currently not supported").arg(arr)) return False self.layout = QGridLayout() self.setLayout(self.layout) self.setWindowIcon(get_icon('arredit.png')) title = self.tr("Array editor") + \ "%s" % (" - "+str(title) if str(title) else "") if readonly: title += ' (' + self.tr('read only') + ')' self.setWindowTitle(title) self.resize(600, 500) # Stack widget self.stack = QStackedWidget(self) if self.is_record_array: for name in data.dtype.names: self.stack.addWidget( ArrayEditorWidget(self, data[name], xy, readonly)) else: self.stack.addWidget(ArrayEditorWidget(self, data, xy, readonly)) self.arraywidget = self.stack.currentWidget() self.connect(self.stack, SIGNAL('currentChanged(int)'), self.current_widget_changed) self.layout.addWidget(self.stack, 1, 0) # Buttons configuration btn_layout = QHBoxLayout() if self.is_record_array: btn_layout.addWidget(QLabel(self.tr("Record array fields:"))) ra_combo = QComboBox(self) self.connect(ra_combo, SIGNAL('currentIndexChanged(int)'), self.stack.setCurrentIndex) names = [] for name in data.dtype.names: field = data.dtype.fields[name] text = name if len(field) >= 3: title = field[2] if not isinstance(title, basestring): title = repr(title) text += ' - ' + title names.append(text) ra_combo.addItems(names) btn_layout.addWidget(ra_combo) btn_layout.addStretch() bbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.connect(bbox, SIGNAL("accepted()"), SLOT("accept()")) self.connect(bbox, SIGNAL("rejected()"), SLOT("reject()")) btn_layout.addWidget(bbox) self.layout.addLayout(btn_layout, 2, 0) self.setMinimumSize(400, 300) # Make the dialog act as a window self.setWindowFlags(Qt.Window) return True
def __init__(self, parent, layer): ''' Constructor ''' QDialog.__init__(self, parent) self.resize(200, 200) self.rasterLayer = layer sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth()) self.setSizePolicy(sizePolicy) verticalLayout = QVBoxLayout(self) verticalLayout.setObjectName("verticalLayout") stackedWidget = QStackedWidget(self) stackedWidget.setObjectName("stackedWidget") pageRender = QWidget(stackedWidget) pageRender.setObjectName("pageRender") sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( pageRender.sizePolicy().hasHeightForWidth()) pageRender.setSizePolicy(sizePolicy) horizontalLayout = QHBoxLayout(pageRender) horizontalLayout.setObjectName("horizontalLayout") frameRender = QFrame(pageRender) frameRender.setObjectName("frameRender") frameRender.setFrameShape(QFrame.StyledPanel) frameRender.setFrameShadow(QFrame.Raised) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( frameRender.sizePolicy().hasHeightForWidth()) frameRender.setSizePolicy(sizePolicy) self.vLayoutFrameRender = QVBoxLayout(frameRender) self.vLayoutFrameRender.setObjectName("vLayoutFrameRender") horizontalLayout.addWidget(frameRender) self.cmbRendererType = ComboBoxPanel(frameRender) self.cmbRendererType.Caption = "Render Type" self.cmbRendererType.LabelWidth = 70 self.cmbRendererType.Items = [ "Mutiband color", "Paletted", "Singleband gray", "Singleband pseudocolor" ] self.connect(self.cmbRendererType, SIGNAL("Event_0"), self.cmbRendererType_currentIndexChanged) self.vLayoutFrameRender.addWidget(self.cmbRendererType) self.gbRenderer = GroupBox(frameRender) self.gbRenderer.Caption = self.cmbRendererType.SelectedItem self.vLayoutFrameRender.addWidget(self.gbRenderer) self.qgsMultiBandColorRendererWidget = QgsMultiBandColorRendererWidget( self.rasterLayer) self.qgsPalettedRendererWidget = QgsPalettedRendererWidget( self.rasterLayer) self.qgsSingleBandGrayRendererWidget = QgsSingleBandGrayRendererWidget( self.rasterLayer) self.qgsSingleBandPseudoColorRendererWidget = QgsSingleBandPseudoColorRendererWidget( self.rasterLayer) self.gbRenderer.Add = self.qgsMultiBandColorRendererWidget self.gbRenderer.Add = self.qgsPalettedRendererWidget self.gbRenderer.Add = self.qgsSingleBandGrayRendererWidget self.gbRenderer.Add = self.qgsSingleBandPseudoColorRendererWidget self.qgsPalettedRendererWidget.setVisible(False) self.qgsSingleBandGrayRendererWidget.setVisible(False) self.qgsSingleBandPseudoColorRendererWidget.setVisible(False) stackedWidget.addWidget(pageRender) # page_2 = QWidget() # page_2.setObjectName("page_2") # stackedWidget.addWidget(page_2) verticalLayout.addWidget(stackedWidget) buttonBox = QDialogButtonBox(self) buttonBox.setObjectName("buttonBox") buttonBox.setOrientation(Qt.Horizontal) buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok | QDialogButtonBox.Apply) btnApply = buttonBox.button(QDialogButtonBox.Apply) btnApply.clicked.connect(self.btnApply_clicked) verticalLayout.addWidget(buttonBox) # retranslateUi(Dialog) buttonBox.accepted.connect(self.OK) buttonBox.rejected.connect(self.reject) if self.rasterLayer.renderer().bandCount() == 1: self.cmbRendererType.SelectedIndex = 2 elif self.rasterLayer.renderer().bandCount() > 1: self.cmbRendererType.SelectedIndex = 0
class ModelerParametersDialog(QDialog): ENTER_NAME = '[Enter name if this is a final result]' NOT_SELECTED = '[Not selected]' USE_MIN_COVERING_EXTENT = '[Use min covering extent]' def __init__(self, alg, model, algName=None): QDialog.__init__(self) self.setModal(True) #The algorithm to define in this dialog. It is an instance of GeoAlgorithm self._alg = alg #The resulting algorithm after the user clicks on OK. it is an instance of the container Algorithm class self.alg = None #The model this algorithm is going to be added to self.model = model #The name of the algorithm in the model, in case we are editing it and not defining it for the first time self._algName = algName self.setupUi() self.params = None def setupUi(self): self.labels = {} self.widgets = {} self.checkBoxes = {} self.showAdvanced = False self.valueItems = {} self.dependentItems = {} self.resize(650, 450) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) tooltips = self._alg.getParameterDescriptions() self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(5) self.verticalLayout.setMargin(20) hLayout = QHBoxLayout() hLayout.setSpacing(5) hLayout.setMargin(0) descriptionLabel = QLabel(self.tr("Description")) self.descriptionBox = QLineEdit() self.descriptionBox.setText(self._alg.name) hLayout.addWidget(descriptionLabel) hLayout.addWidget(self.descriptionBox) self.verticalLayout.addLayout(hLayout) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.verticalLayout.addWidget(line) for param in self._alg.parameters: if param.isAdvanced: self.advancedButton = QPushButton() self.advancedButton.setText( self.tr('Show advanced parameters')) self.advancedButton.setMaximumWidth(150) self.advancedButton.clicked.connect( self.showAdvancedParametersClicked) self.verticalLayout.addWidget(self.advancedButton) break for param in self._alg.parameters: if param.hidden: continue desc = param.description if isinstance(param, ParameterExtent): desc += '(xmin, xmax, ymin, ymax)' label = QLabel(desc) self.labels[param.name] = label widget = self.getWidgetFromParameter(param) self.valueItems[param.name] = widget if param.name in tooltips.keys(): tooltip = tooltips[param.name] else: tooltip = param.description label.setToolTip(tooltip) widget.setToolTip(tooltip) if param.isAdvanced: label.setVisible(self.showAdvanced) widget.setVisible(self.showAdvanced) self.widgets[param.name] = widget self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(widget) for output in self._alg.outputs: if output.hidden: continue if isinstance(output, (OutputRaster, OutputVector, OutputTable, OutputHTML, OutputFile, OutputDirectory)): label = QLabel(output.description + '<' + output.__class__.__name__ + '>') item = QLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME) self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(item) self.valueItems[output.name] = item label = QLabel(' ') self.verticalLayout.addWidget(label) label = QLabel(self.tr('Parent algorithms')) self.dependenciesPanel = self.getDependenciesPanel() self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(self.dependenciesPanel) self.verticalLayout.addStretch(1000) self.setLayout(self.verticalLayout) self.setPreviousValues() self.setWindowTitle(self._alg.name) self.verticalLayout2 = QVBoxLayout() self.verticalLayout2.setSpacing(2) self.verticalLayout2.setMargin(0) self.tabWidget = QTabWidget() self.tabWidget.setMinimumWidth(300) self.paramPanel = QWidget() self.paramPanel.setLayout(self.verticalLayout) self.scrollArea = QScrollArea() self.scrollArea.setWidget(self.paramPanel) self.scrollArea.setWidgetResizable(True) self.tabWidget.addTab(self.scrollArea, self.tr('Parameters')) self.webView = QWebView() html = None url = None isText, help = self._alg.help() if help is not None: if isText: html = help else: url = QUrl(help) else: html = self.tr('<h2>Sorry, no help is available for this ' 'algorithm.</h2>') try: if html: self.webView.setHtml(html) elif url: self.webView.load(url) except: self.webView.setHtml( self.tr('<h2>Could not open help file :-( </h2>')) self.tabWidget.addTab(self.webView, 'Help') self.verticalLayout2.addWidget(self.tabWidget) self.verticalLayout2.addWidget(self.buttonBox) self.setLayout(self.verticalLayout2) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) QMetaObject.connectSlotsByName(self) def getAvailableDependencies(self): if self._algName is None: dependent = [] else: dependent = self.model.getDependentAlgorithms(self._algName) opts = [] for alg in self.model.algs.values(): if alg.name not in dependent: opts.append(alg) return opts def getDependenciesPanel(self): return MultipleInputPanel( [alg.algorithm.name for alg in self.getAvailableDependencies()]) def showAdvancedParametersClicked(self): self.showAdvanced = not self.showAdvanced if self.showAdvanced: self.advancedButton.setText(self.tr('Hide advanced parameters')) else: self.advancedButton.setText(self.tr('Show advanced parameters')) for param in self._alg.parameters: if param.isAdvanced: self.labels[param.name].setVisible(self.showAdvanced) self.widgets[param.name].setVisible(self.showAdvanced) def getAvailableValuesOfType(self, paramType, outType=None): values = [] inputs = self.model.inputs for i in inputs.values(): param = i.param if isinstance(param, paramType): values.append(ValueFromInput(param.name)) if outType is None: return values if self._algName is None: dependent = [] else: dependent = self.model.getDependentAlgorithms(self._algName) for alg in self.model.algs.values(): if alg.name not in dependent: for out in alg.algorithm.outputs: if isinstance(out, outType): values.append(ValueFromOutput(alg.name, out.name)) return values def resolveValueDescription(self, value): if isinstance(value, ValueFromInput): return self.model.inputs[value.name].param.description else: alg = self.model.algs[value.alg] return self.tr("'%s' from algorithm '%s'") % ( alg.algorithm.getOutputFromName( value.output).description, alg.description) def getWidgetFromParameter(self, param): if isinstance(param, ParameterRaster): item = QComboBox() layers = self.getAvailableValuesOfType(ParameterRaster, OutputRaster) if param.optional: item.addItem(self.NOT_SELECTED, None) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterVector): item = QComboBox() layers = self.getAvailableValuesOfType(ParameterVector, OutputVector) if param.optional: item.addItem(self.NOT_SELECTED, None) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterTable): item = QComboBox() tables = self.getAvailableValuesOfType(ParameterTable, OutputTable) layers = self.getAvailableValuesOfType(ParameterVector, OutputVector) if param.optional: item.addItem(self.NOT_SELECTED, None) for table in tables: item.addItem(self.resolveValueDescription(table), table) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterBoolean): item = QComboBox() item.addItem('Yes') item.addItem('No') bools = self.getAvailableValuesOfType(ParameterBoolean, None) for b in bools: item.addItem(self.resolveValueDescription(b), b) elif isinstance(param, ParameterSelection): item = QComboBox() item.addItems(param.options) item.setCurrentIndex(param.default) elif isinstance(param, ParameterFixedTable): item = FixedTablePanel(param) elif isinstance(param, ParameterRange): item = RangePanel(param) elif isinstance(param, ParameterMultipleInput): if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = self.getAvailableValuesOfType( ParameterVector, OutputVector) else: options = self.getAvailableValuesOfType( ParameterRaster, OutputRaster) opts = [] for opt in options: opts.append(self.resolveValueDescription(opt)) item = MultipleInputPanel(opts) elif isinstance(param, ParameterString): strings = self.getAvailableValuesOfType(ParameterString, OutputString) options = [(self.resolveValueDescription(s), s) for s in strings] if param.multiline: item = MultilineTextPanel(options) item.setText(unicode(param.default)) else: item = QComboBox() item.setEditable(True) for desc, val in options: item.addItem(desc, val) item.setEditText(unicode(param.default)) elif isinstance(param, ParameterTableField): item = QComboBox() item.setEditable(True) fields = self.getAvailableValuesOfType(ParameterTableField, None) for f in fields: item.addItem(self.resolveValueDescription(f), f) elif isinstance(param, ParameterNumber): item = QComboBox() item.setEditable(True) numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber) for n in numbers: item.addItem(self.resolveValueDescription(n), n) item.setEditText(unicode(param.default)) elif isinstance(param, ParameterCrs): item = CrsSelectionPanel(param.default) elif isinstance(param, ParameterExtent): item = QComboBox() item.setEditable(True) extents = self.getAvailableValuesOfType(ParameterExtent, OutputExtent) if self.canUseAutoExtent(): item.addItem(self.USE_MIN_COVERING_EXTENT, None) for ex in extents: item.addItem(self.resolveValueDescription(ex), ex) if not self.canUseAutoExtent(): item.setEditText(unicode(param.default)) elif isinstance(param, ParameterFile): item = QComboBox() item.setEditable(True) files = self.getAvailableValuesOfType(ParameterFile, OutputFile) for f in files: item.addItem(self.resolveValueDescription(f), f) elif isinstance(param, ParameterGeometryPredicate): item = GeometryPredicateSelectionPanel(param.enabledPredicates) else: item = QLineEdit() try: item.setText(unicode(param.default)) except: pass return item def canUseAutoExtent(self): for param in self._alg.parameters: if isinstance( param, (ParameterRaster, ParameterVector, ParameterMultipleInput)): return True return False def setTableContent(self): params = self._alg.parameters outputs = self._alg.outputs visibleParams = [p for p in params if not p.hidden] visibleOutputs = [p for o in outputs if not o.hidden] self.tableWidget.setRowCount(len(visibleParams) + len(visibleOutputs)) for i, param in visibleParams: item = QTableWidgetItem(param.description) item.setFlags(Qt.ItemIsEnabled) self.tableWidget.setItem(i, 0, item) item = self.getWidgetFromParameter(param) self.valueItems[param.name] = item self.tableWidget.setCellWidget(i, 1, item) self.tableWidget.setRowHeight(i, 22) for i, output in visibleOutputs: item = QTableWidgetItem(output.description + '<' + output.__module__.split('.')[-1] + '>') item.setFlags(Qt.ItemIsEnabled) self.tableWidget.setItem(i, 0, item) item = QLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME) self.valueItems[output.name] = item self.tableWidget.setCellWidget(i, 1, item) self.tableWidget.setRowHeight(i, 22) def setComboBoxValue(self, combo, value, param): if isinstance(value, list): value = value[0] items = [combo.itemData(i) for i in range(combo.count())] try: idx = items.index(value) combo.setCurrentIndex(idx) return except ValueError: pass if combo.isEditable(): if value is not None: combo.setEditText(unicode(value)) elif isinstance(param, ParameterSelection): combo.setCurrentIndex(int(value)) elif isinstance(param, ParameterBoolean): if value: combo.setCurrentIndex(0) else: combo.setCurrentIndex(1) def setPreviousValues(self): if self._algName is not None: alg = self.model.algs[self._algName] self.descriptionBox.setText(alg.description) for param in alg.algorithm.parameters: if param.hidden: continue widget = self.valueItems[param.name] if param.name in alg.params: value = alg.params[param.name] else: value = None if isinstance( param, (ParameterRaster, ParameterVector, ParameterTable, ParameterTableField, ParameterSelection, ParameterNumber, ParameterBoolean, ParameterExtent, ParameterFile)): self.setComboBoxValue(widget, value, param) elif isinstance(param, ParameterString): if param.multiline: widget.setValue(value) else: self.setComboBoxValue(widget, value, param) elif isinstance(param, ParameterCrs): widget.setAuthId(value) elif isinstance(param, ParameterFixedTable): pass # TODO! elif isinstance(param, ParameterMultipleInput): if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = self.getAvailableValuesOfType( ParameterVector, OutputVector) else: options = self.getAvailableValuesOfType( ParameterRaster, OutputRaster) selected = [] for i, opt in enumerate(options): if opt in value: selected.append(i) widget.setSelectedItems(selected) elif isinstance(param, ParameterGeometryPredicate): widget.setValue(value) for name, out in alg.outputs.iteritems(): widget = self.valueItems[name].setText(out.description) selected = [] dependencies = self.getAvailableDependencies() for idx, dependency in enumerate(dependencies): if dependency in alg.dependencies: selected.append(idx) self.dependenciesPanel.setSelectedItems(selected) def createAlgorithm(self): alg = Algorithm(self._alg.commandLineName()) alg.setName(self.model) alg.description = self.descriptionBox.text() params = self._alg.parameters outputs = self._alg.outputs for param in params: if param.hidden: continue if not self.setParamValue(alg, param, self.valueItems[param.name]): return None for output in outputs: if not output.hidden: name = unicode(self.valueItems[output.name].text()) if name.strip( ) != '' and name != ModelerParametersDialog.ENTER_NAME: alg.outputs[output.name] = ModelerOutput(name) selectedOptions = self.dependenciesPanel.selectedoptions availableDependencies = self.getAvailableDependencies() for selected in selectedOptions: alg.dependencies.append(availableDependencies[selected].name) return alg def setParamValueLayerOrTable(self, alg, param, widget): idx = widget.currentIndex() if idx < 0: return False else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamTableFieldValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = unicode(widget.currentText()).strip() if s == '': if param.optional: alg.params[param.name] = None return True else: return False else: alg.params[param.name] = s return True else: alg.params[param.name] = widget.itemData(widget.currentIndex()) return True def setParamStringValue(self, alg, param, widget): if param.multiline: value = widget.getValue() option = widget.getOption() if option == MultilineTextPanel.USE_TEXT: if value == '': if param.optional: alg.params[param.name] = None return True else: return False else: alg.params[param.name] = value else: alg.params[param.name] = value else: idx = widget.findText(widget.currentText()) if idx < 0: value = widget.currentText().strip() if value == '': if param.optional: alg.params[param.name] = None return True else: return False else: alg.params[param.name] = value else: alg.params[param.name] = widget.itemData(widget.currentIndex()) return True def setParamFileValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: value = widget.currentText() else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamNumberValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = widget.currentText() try: value = float(s) except: return False else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamExtentValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = unicode(widget.currentText()) try: tokens = s.split(',') if len(tokens) != 4: return False for token in tokens: float(token) except: return False alg.params[param.name] = [s] else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamValue(self, alg, param, widget): if isinstance(param, (ParameterRaster, ParameterVector, ParameterTable)): return self.setParamValueLayerOrTable(alg, param, widget) elif isinstance(param, ParameterBoolean): if widget.currentIndex() < 2: value = widget.currentIndex() == 0 else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True elif isinstance(param, ParameterString): return self.setParamStringValue(alg, param, widget) elif isinstance(param, ParameterNumber): return self.setParamNumberValue(alg, param, widget) elif isinstance(param, ParameterExtent): return self.setParamExtentValue(alg, param, widget) elif isinstance(param, ParameterFile): return self.setParamFileValue(alg, param, widget) elif isinstance(param, ParameterSelection): alg.params[param.name] = widget.currentIndex() return True elif isinstance(param, ParameterRange): alg.params[param.name] = widget.getValue() return True elif isinstance(param, ParameterCrs): authid = widget.getValue() if authid is None: alg.params[param.name] = None else: alg.params[param.name] = authid return True elif isinstance(param, ParameterFixedTable): alg.params[param.name] = ParameterFixedTable.tableToString( widget.table) return True elif isinstance(param, ParameterTableField): return self.setParamTableFieldValue(alg, param, widget) elif isinstance(param, ParameterMultipleInput): if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = self.getAvailableValuesOfType( ParameterVector, OutputVector) else: options = self.getAvailableValuesOfType( ParameterRaster, OutputRaster) values = [options[i] for i in widget.selectedoptions] if len(values) == 0 and not param.optional: return False alg.params[param.name] = values return True elif isinstance(param, ParameterGeometryPredicate): alg.params[param.name] = widget.value() return True else: alg.params[param.name] = unicode(widget.text()) return True def okPressed(self): self.alg = self.createAlgorithm() if self.alg is not None: self.close() else: QMessageBox.warning(self, self.tr('Unable to add algorithm'), self.tr('Wrong or missing parameter values')) def cancelPressed(self): self.alg = None self.close()
def setupUi(self): self.labels = {} self.widgets = {} self.checkBoxes = {} self.showAdvanced = False self.valueItems = {} self.dependentItems = {} self.resize(650, 450) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) tooltips = self._alg.getParameterDescriptions() self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(5) self.verticalLayout.setMargin(20) hLayout = QHBoxLayout() hLayout.setSpacing(5) hLayout.setMargin(0) descriptionLabel = QLabel(self.tr("Description")) self.descriptionBox = QLineEdit() self.descriptionBox.setText(self._alg.name) hLayout.addWidget(descriptionLabel) hLayout.addWidget(self.descriptionBox) self.verticalLayout.addLayout(hLayout) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.verticalLayout.addWidget(line) for param in self._alg.parameters: if param.isAdvanced: self.advancedButton = QPushButton() self.advancedButton.setText( self.tr('Show advanced parameters')) self.advancedButton.setMaximumWidth(150) self.advancedButton.clicked.connect( self.showAdvancedParametersClicked) self.verticalLayout.addWidget(self.advancedButton) break for param in self._alg.parameters: if param.hidden: continue desc = param.description if isinstance(param, ParameterExtent): desc += '(xmin, xmax, ymin, ymax)' label = QLabel(desc) self.labels[param.name] = label widget = self.getWidgetFromParameter(param) self.valueItems[param.name] = widget if param.name in tooltips.keys(): tooltip = tooltips[param.name] else: tooltip = param.description label.setToolTip(tooltip) widget.setToolTip(tooltip) if param.isAdvanced: label.setVisible(self.showAdvanced) widget.setVisible(self.showAdvanced) self.widgets[param.name] = widget self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(widget) for output in self._alg.outputs: if output.hidden: continue if isinstance(output, (OutputRaster, OutputVector, OutputTable, OutputHTML, OutputFile, OutputDirectory)): label = QLabel(output.description + '<' + output.__class__.__name__ + '>') item = QLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME) self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(item) self.valueItems[output.name] = item label = QLabel(' ') self.verticalLayout.addWidget(label) label = QLabel(self.tr('Parent algorithms')) self.dependenciesPanel = self.getDependenciesPanel() self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(self.dependenciesPanel) self.verticalLayout.addStretch(1000) self.setLayout(self.verticalLayout) self.setPreviousValues() self.setWindowTitle(self._alg.name) self.verticalLayout2 = QVBoxLayout() self.verticalLayout2.setSpacing(2) self.verticalLayout2.setMargin(0) self.tabWidget = QTabWidget() self.tabWidget.setMinimumWidth(300) self.paramPanel = QWidget() self.paramPanel.setLayout(self.verticalLayout) self.scrollArea = QScrollArea() self.scrollArea.setWidget(self.paramPanel) self.scrollArea.setWidgetResizable(True) self.tabWidget.addTab(self.scrollArea, self.tr('Parameters')) self.webView = QWebView() html = None url = None isText, help = self._alg.help() if help is not None: if isText: html = help else: url = QUrl(help) else: html = self.tr('<h2>Sorry, no help is available for this ' 'algorithm.</h2>') try: if html: self.webView.setHtml(html) elif url: self.webView.load(url) except: self.webView.setHtml( self.tr('<h2>Could not open help file :-( </h2>')) self.tabWidget.addTab(self.webView, 'Help') self.verticalLayout2.addWidget(self.tabWidget) self.verticalLayout2.addWidget(self.buttonBox) self.setLayout(self.verticalLayout2) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) QMetaObject.connectSlotsByName(self)
def _init_layout(self): """ Create the GUI widgets (but leave them empty). """ hostname_combobox = QComboBox(parent=self) self._hostname_combobox = hostname_combobox hostname_combobox.setEditable(True) hostname_combobox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum) hostname_combobox.installEventFilter(self) for hostname in self._suggested_hostnames: hostname_combobox.addItem(hostname) self._connect_button = QPushButton("Connect", parent=self, clicked=self._handle_new_hostname) hostname_layout = QHBoxLayout() hostname_layout.addWidget(hostname_combobox) hostname_layout.addWidget(self._connect_button) hostname_groupbox = QGroupBox("DVID Host", parent=self) hostname_groupbox.setLayout(hostname_layout) hostname_groupbox.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum) data_treewidget = QTreeWidget(parent=self) data_treewidget.setHeaderLabels( ["Data"]) # TODO: Add type, shape, axes, etc. data_treewidget.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) data_treewidget.itemSelectionChanged.connect( self._handle_data_selection) data_layout = QVBoxLayout() data_layout.addWidget(data_treewidget) data_groupbox = QGroupBox("Data Volumes", parent=self) data_groupbox.setLayout(data_layout) node_listwidget = QListWidget(parent=self) node_listwidget.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) node_listwidget.itemSelectionChanged.connect(self._update_display) node_layout = QVBoxLayout() node_layout.addWidget(node_listwidget) node_groupbox = QGroupBox("Nodes", parent=self) node_groupbox.setLayout(node_layout) new_data_edit = QLineEdit(parent=self) new_data_edit.textEdited.connect(self._update_display) full_url_label = QLabel(parent=self) full_url_label.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum) text_flags = full_url_label.textInteractionFlags() full_url_label.setTextInteractionFlags(text_flags | Qt.TextSelectableByMouse) new_data_layout = QVBoxLayout() new_data_layout.addWidget(new_data_edit) new_data_groupbox = QGroupBox("New Data Volume", parent=self) new_data_groupbox.setLayout(new_data_layout) new_data_groupbox.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum) buttonbox = QDialogButtonBox(Qt.Horizontal, parent=self) buttonbox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonbox.accepted.connect(self.accept) buttonbox.rejected.connect(self.reject) buttonbox.button(QDialogButtonBox.Ok).setEnabled(False) layout = QVBoxLayout() layout.addWidget(hostname_groupbox) layout.addWidget(data_groupbox) layout.addWidget(node_groupbox) if self._mode == "specify_new": layout.addWidget(new_data_groupbox) else: new_data_groupbox.hide() layout.addWidget(full_url_label) layout.addWidget(buttonbox) # Stretch factors layout.setStretchFactor(data_groupbox, 3) layout.setStretchFactor(node_groupbox, 1) self.setLayout(layout) self.setWindowTitle("Select DVID Volume") # Initially disabled data_groupbox.setEnabled(False) node_groupbox.setEnabled(False) new_data_groupbox.setEnabled(False) # Save instance members self._data_groupbox = data_groupbox self._node_groupbox = node_groupbox self._new_data_groupbox = new_data_groupbox self._data_treewidget = data_treewidget self._node_listwidget = node_listwidget self._new_data_edit = new_data_edit self._full_url_label = full_url_label self._buttonbox = buttonbox
def __init__(self, parent): QDialog.__init__(self, parent) self.prm = parent.prm self.currLocale = self.parent().prm['data']['currentLocale'] self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator) vbl = QVBoxLayout() self.grid = QGridLayout() # Noise Type noiseTypeLabel = QLabel(self.tr('Noise Type: ')) self.noiseTypeChooser = QComboBox() self.noiseTypeChooser.addItems([self.tr('White'), self.tr('Pink'), self.tr("Red"), self.tr("Blue"), self.tr("Violet")]) self.noiseTypeChooser.setCurrentIndex(0) self.grid.addWidget(noiseTypeLabel, 0, 0) self.grid.addWidget(self.noiseTypeChooser, 0, 1) self.noiseTypeChooser.currentIndexChanged[int].connect(self.onChangeNoiseType) #Noise Label noiseLabelLabel = QLabel(self.tr('Sound Label: ')) self.noiseLabelWidget = QLineEdit(self.tr('Noise')) self.grid.addWidget(noiseLabelLabel, 0, 2) self.grid.addWidget(self.noiseLabelWidget, 0, 3) # Noise Duration noiseDurationLabel = QLabel(self.tr('Duration (ms):')) defaultDuration = 980 self.noiseDurationWidget = QLineEdit(self.currLocale.toString(defaultDuration)) self.noiseDurationWidget.setValidator(QDoubleValidator(self)) self.grid.addWidget(noiseDurationLabel, 1, 0) self.grid.addWidget(self.noiseDurationWidget, 1, 1) #Noise Ramps noiseRampsLabel = QLabel(self.tr('Ramps (ms):')) defaultRamps = 10 self.noiseRampsWidget = QLineEdit(self.currLocale.toString(defaultRamps)) self.noiseRampsWidget.setValidator(QDoubleValidator(self)) self.grid.addWidget(noiseRampsLabel, 1, 2) self.grid.addWidget(self.noiseRampsWidget, 1, 3) #Noise Spectrum Level noiseLevelLabel = QLabel(self.tr('Spectrum Level (dB):')) defaultSpectrumLevel = 40 self.noiseLevelWidget = QLineEdit(self.currLocale.toString(defaultSpectrumLevel)) self.noiseLevelWidget.setValidator(QIntValidator(self)) self.grid.addWidget(noiseLevelLabel, 2, 0) self.grid.addWidget(self.noiseLevelWidget, 2, 1) #Noise Sampling Rate sampRateLabel = QLabel(self.tr('Sampling Rate')) defaultSampRate = 48000 self.sampRateWidget = QLineEdit(self.currLocale.toString(defaultSampRate)) self.sampRateWidget.setValidator(QIntValidator(self)) self.grid.addWidget(sampRateLabel, 3, 0) self.grid.addWidget(self.sampRateWidget, 3, 1) #Ear noiseEarLabel = QLabel(self.tr('Ear: ')) self.noiseEarChooser = QComboBox() self.noiseEarChooser.addItems([self.tr('Right'), self.tr('Left'), self.tr('Both')]) self.noiseEarChooser.setCurrentIndex(0) self.grid.addWidget(noiseEarLabel, 3, 2) self.grid.addWidget(self.noiseEarChooser, 3, 3) self.currNoiseType = self.tr('White') buttonBox = QDialogButtonBox(QDialogButtonBox.Ok| QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) vbl.addLayout(self.grid) vbl.addWidget(buttonBox) self.setLayout(vbl) self.setWindowTitle(self.tr("Generate Noise"))
def __init__(self, parent, title, valueList=None): QDialog.__init__(self, parent) self.resize(100, 70) self.setWindowTitle(title) 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.frameBasic = Frame(self) verticalLayoutDlg.addWidget(self.frameBasic) self.pnlName = TextBoxPanel(self.frameBasic) self.pnlName.Caption = "Name" self.pnlName.LabelWidth = 120 self.frameBasic.Add = self.pnlName self.pnlObstacle = PositionPanel(self.frameBasic, None, None, "Degree") self.pnlObstacle.btnCalculater.setVisible(False) self.frameBasic.Add = self.pnlObstacle self.pnlType = ComboBoxPanel(self.frameBasic) self.pnlType.Caption = "Type" self.pnlType.LabelWidth = 120 self.frameBasic.Add = self.pnlType self.pnlRemarks = TextBoxPanel(self.frameBasic, True) self.pnlRemarks.Caption = "Remarks" self.pnlRemarks.LabelWidth = 120 self.frameBasic.Add = self.pnlRemarks self.btnBoxOkCancel = QDialogButtonBox(self) self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel")) self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg) self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject) verticalLayoutDlg.addWidget(self.btnBoxOkCancel) self.name = "" self.latitude = "" self.longitude = "" self.altitude = "" self.type = "" self.remarks = "" if title == "Add Symbol" or title == "Modify Symbol": self.pnlType.Items = [ SymbolType.Default, SymbolType.Arp, SymbolType.Be1, SymbolType.Dme, SymbolType.Faf, SymbolType.Gp, SymbolType.Ndb, SymbolType.Repnc, SymbolType.Tacan, SymbolType.Vor, SymbolType.Vord ] elif title == "Add Obstacle" or title == "Modify Obstacle": self.pnlType.Items = [ SymbolType.Obst1, SymbolType.Obst2, SymbolType.Obst3, SymbolType.Obst4 ] self.editingFlag = False if valueList != None: self.pnlName.Value = valueList[0] self.pnlObstacle.Point3d = Point3D(float(valueList[2]), float(valueList[1]), float(valueList[3])) self.pnlType.Value = valueList[4] self.pnlRemarks.Value = valueList[5] self.editingFlag = True
def __init__(self, parent): QDialog.__init__(self, parent) self.prm = self.parent().prm self.tmpPref = {} self.tmpPref['experimenter'] = {} self.tmpPref['experimenter'] = copy.deepcopy(self.parent().prm['experimenter']) self.currLocale = self.parent().prm['currentLocale'] self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator) self.sizer = QGridLayout() self.h1Sizer = QHBoxLayout() self.v1Sizer = QVBoxLayout() self.v2Sizer = QVBoxLayout() n = 0 self.experimenterLabel = QLabel(self.tr("Experimenter ID:"), self) self.sizer.addWidget(self.experimenterLabel, n, 0) self.experimenterChooser = QComboBox() self.experimenterChooser.addItems(self.tmpPref['experimenter']['experimenter_id']) self.sizer.addWidget(self.experimenterChooser, n, 1) self.experimenterChooser.activated[str].connect(self.onExperimenterChange) self.currIdx = self.experimenterChooser.currentIndex() n = n+1 self.experimenterNameLabel = QLabel(self.tr("Name:"), self) self.sizer.addWidget(self.experimenterNameLabel, n, 0) self.experimenterNameTF = QLineEdit("") self.experimenterNameTF.setText(self.tmpPref['experimenter']['experimenter_name'][0]) self.sizer.addWidget(self.experimenterNameTF, n, 1) n = n+1 self.experimenterSurnameLabel = QLabel(self.tr("Surname:"), self) self.sizer.addWidget(self.experimenterSurnameLabel, n, 0) self.experimenterSurnameTF = QLineEdit("") self.experimenterSurnameTF.setText(self.tmpPref['experimenter']['experimenter_surname'][0]) self.sizer.addWidget(self.experimenterSurnameTF, n, 1) n = n+1 self.experimenterEmailLabel = QLabel(self.tr("e-mail:"), self) self.sizer.addWidget(self.experimenterEmailLabel, n, 0) self.experimenterEmailTF = QLineEdit("") self.experimenterEmailTF.setText(self.tmpPref['experimenter']['experimenter_email'][0]) self.sizer.addWidget(self.experimenterEmailTF, n, 1) n = n+1 self.experimenterAddressLabel = QLabel(self.tr("Address (line 1):"), self) self.sizer.addWidget(self.experimenterAddressLabel, n, 0) self.experimenterAddressTF = QLineEdit("") self.experimenterAddressTF.setText(self.tmpPref['experimenter']['experimenter_address'][0]) self.sizer.addWidget(self.experimenterAddressTF, n, 1) n = n+1 self.experimenterAddressLabel2 = QLabel(self.tr("Address (line 2):"), self) self.sizer.addWidget(self.experimenterAddressLabel2, n, 0) self.experimenterAddressTF2 = QLineEdit("") self.experimenterAddressTF2.setText(self.tmpPref['experimenter']['experimenter_address2'][0]) self.sizer.addWidget(self.experimenterAddressTF2, n, 1) n = n+1 self.experimenterTelephoneLabel = QLabel(self.tr("Telephone:"), self) self.sizer.addWidget(self.experimenterTelephoneLabel, n, 0) self.experimenterTelephoneTF = QLineEdit("") self.experimenterTelephoneTF.setText(self.tmpPref['experimenter']['experimenter_telephone'][0]) self.sizer.addWidget(self.experimenterTelephoneTF, n, 1) n = n+1 self.experimenterMobileLabel = QLabel(self.tr("Mobile:"), self) self.sizer.addWidget(self.experimenterMobileLabel, n, 0) self.experimenterMobileTF = QLineEdit("") self.experimenterMobileTF.setText(self.tmpPref['experimenter']['experimenter_mobile'][0]) self.sizer.addWidget(self.experimenterMobileTF, n, 1) #ADD EXPERIMENTER BUTTON addExpButton = QPushButton(self.tr("Add Experimenter"), self) addExpButton.clicked.connect(self.onClickAddExpButton) self.v2Sizer.addWidget(addExpButton) #REMOVE EXPERIMENTER BUTTON removeExpButton = QPushButton(self.tr("Remove Experimenter"), self) removeExpButton.clicked.connect(self.onClickRemoveExpButton) self.v2Sizer.addWidget(removeExpButton) #CHANGE ID BUTTON changeIdButton = QPushButton(self.tr("Change Identifier"), self) changeIdButton.clicked.connect(self.onClickChangeIdButton) self.v2Sizer.addWidget(changeIdButton) #SET AS DEFAULT BUTTON setAsDefaultButton = QPushButton(self.tr("Set as default"), self) setAsDefaultButton.clicked.connect(self.onClickSetAsDefaultButton) self.v2Sizer.addWidget(setAsDefaultButton) self.v2Sizer.addStretch() buttonBox = QDialogButtonBox(QDialogButtonBox.Apply|QDialogButtonBox.Ok|QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) buttonBox.button(QDialogButtonBox.Apply).clicked.connect(self.onClickApplyButton) self.h1Sizer.addLayout(self.v2Sizer) self.sizer.setAlignment(Qt.AlignTop) self.h1Sizer.addLayout(self.sizer) self.v1Sizer.addLayout(self.h1Sizer) self.v1Sizer.addWidget(buttonBox) self.setLayout(self.v1Sizer)
def __init__(self, parent, sndType): QDialog.__init__(self, parent) self.prm = parent.prm self.currLocale = self.parent().prm['data']['currentLocale'] self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator) self.vbl = QVBoxLayout() self.hbl = QHBoxLayout() self.grid_0 = QGridLayout() self.grid_1 = QGridLayout() if sndType == "Harmonic Complex": self.execString = "harm_compl" elif sndType == "Silence": self.execString = "silence" elif sndType == "FM Tone": self.execString = "fm_tone" elif sndType == "AM Tone": self.execString = "am_tone" self.nrows = 0 #SOUND LABEL soundLabelLabel = QLabel(self.tr('Sound Label: ')) self.soundLabelWidget = QLineEdit(self.tr(sndType)) self.grid_0.addWidget(soundLabelLabel, self.nrows, 0) self.grid_0.addWidget(self.soundLabelWidget, self.nrows, 1) self.nrows = self.nrows + 1 #SAMPLING RATE sampRateLabel = QLabel(self.tr('Sampling Rate')) defaultSampRate = 48000 self.sampRateWidget = QLineEdit(self.currLocale.toString(defaultSampRate)) self.sampRateWidget.setValidator(QIntValidator(self)) self.grid_0.addWidget(sampRateLabel, self.nrows, 0) self.grid_0.addWidget(self.sampRateWidget, self.nrows, 1) self.nrows = self.nrows + 1 methodToCall = getattr(self, "select_default_parameters_" + self.execString) self.sndPrm = methodToCall() self.setDefaultParameters() buttonBox = QDialogButtonBox(QDialogButtonBox.Ok| QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) self.grid_0.setAlignment(Qt.AlignTop) self.grid_1.setAlignment(Qt.AlignTop) self.hbl.addLayout(self.grid_0) self.hbl.addLayout(self.grid_1) self.scrollAreaWidgetContents = QWidget()#QFrame() #self.scrollAreaWidgetContents.setFrameStyle(QFrame.StyledPanel|QFrame.Sunken) self.scrollAreaWidgetContents.setLayout(self.hbl) self.scrollArea = QScrollArea() #self.scrollArea.setWidgetResizable(True) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.scrollAreaWidgetContents.layout().setSizeConstraint(QLayout.SetFixedSize) self.vbl.addWidget(self.scrollArea) self.vbl.addWidget(buttonBox) self.setLayout(self.vbl) screen = QDesktopWidget().screenGeometry() self.resize(int(0.3*screen.width()), int(0.5*screen.height())) self.setWindowTitle(self.tr("Generate Sound"))
class MainWidget(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.configOptions, self.checkBoxList, self.configBool = {}, {}, None # Check for root privileges if geteuid() != 0: msg = ("{} is not root. You need to run with root priviliges\n" "Please use kdesudo, gksu or sudo/sux.").format(getuser()) QMessageBox.critical(self, __doc__ + "- Error", msg) sys.exit(1) else: msg = "This tool is running with root priviliges." QMessageBox.warning(self, __doc__ + "- Warning", msg) # title, icon and sizes self.setWindowTitle(__doc__) self.setMinimumSize(400, 400) self.setMaximumSize(2048, 2048) self.resize(600, 600) self.setWindowIcon(QIcon.fromTheme("preferences-system")) self.menuBar().addMenu("&File").addAction("Exit", exit) QShortcut("Ctrl+q", self, activated=lambda: self.close()) # main group main_group = QGroupBox("Module configuration") self.setCentralWidget(main_group) self.layout = QVBoxLayout(main_group) # scrollarea widgets self.scrollArea, self.window = QScrollArea(), QWidget() self.layout.addWidget(self.scrollArea) self.vbox = QVBoxLayout(self.window) # Graphic effect glow = QGraphicsDropShadowEffect(self) glow.setOffset(0) glow.setBlurRadius(99) glow.setColor(QColor(99, 255, 255)) self.scrollArea.setGraphicsEffect(glow) glow.setEnabled(True) # config loading stuff self.findConfig(CONFIG_DIR) for eachOption in tuple(self.configOptions.keys()): self.readConfig(eachOption, self.configOptions) self.subLayout = QHBoxLayout() self.checkBoxName = "checkBox_" + eachOption checkBoxList = QCheckBox(self.checkBoxName, self) self.checkBoxList[self.checkBoxName] = checkBoxList checkBoxList.setObjectName(self.checkBoxName) checkBoxList.setText("Enable module {}".format(eachOption)) if self.tooltip is not '': checkBoxList.setToolTip(self.tooltip) else: tooltip = "Configuration settings for {}".format(eachOption) checkBoxList.setToolTip(tooltip) if self.configBool: checkBoxList.setChecked(True) self.subLayout.addWidget(checkBoxList) self.vbox.addLayout(self.subLayout) self.scrollArea.setWidget(self.window) # Bottom Buttons Bar self.pushButtonSleep = QPushButton("Sleep") self.pushButtonSleep.setToolTip("Trigger Suspend to RAM aka Sleep") self.pushButtonSleep.clicked.connect(self.sleep) self.pushButtonHibernate = QPushButton("Hibernate") self.pushButtonHibernate.setToolTip( "Trigger Suspend to Disk Hibernate") self.pushButtonHibernate.clicked.connect(self.hibernate) self.buttonBox = QDialogButtonBox() self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Close | QDialogButtonBox.Help) self.buttonBox.addButton(self.pushButtonHibernate, QDialogButtonBox.ActionRole) self.buttonBox.addButton(self.pushButtonSleep, QDialogButtonBox.ActionRole) self.layout.addWidget(self.buttonBox) self.buttonBox.rejected.connect(exit) self.buttonBox.accepted.connect(self.writeConfig) self.buttonBox.helpRequested.connect(lambda: open_new_tab(WEBPAGE_URL)) def closeEvent(self, event): ' Ask to Quit ' the_conditional_is_true = QMessageBox.question( self, __doc__.title(), 'Quit ?.', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) == QMessageBox.Yes event.accept() if the_conditional_is_true else event.ignore() def sleep(self): """Method to make the computer Sleep.""" try: sysfsFP = open("/sys/power/state", 'w') except: log.err("Couldn't open kernel interface") return False else: try: sysfsFP.write("mem") except: log.err("Couldn't write to kernel interface") return False def hibernate(self): """Method to make the computer Hibernate.""" try: sysfsFP = open("/sys/power/state", 'w') except: log.err("Couldn't open kernel interface") return False else: try: sysfsFP.write("disk") except: log.err("Couldn't write to kernel interface") return False def writeConfig(self): """Method to get a configuration for the App.""" finalResult = True for eachWriteOption in tuple(self.configOptions.keys()): checkBoxName = "checkBox_" + eachWriteOption if self.checkBoxList[checkBoxName].isChecked() is True: val = 1 else: val = 0 ret = self.populateValues(self.configOptions[eachWriteOption], val) if ret is False: log.debug("Couldn't apply setting for %s" % checkBoxName) finalResult = False if finalResult is False: QMessageBox.critical(self, "Error", "Couldn't apply all requested settings") else: QMessageBox.information(self, "Success", "Applied all requested settings") def populateValues(self, _path, value): """Method to populate values from a file path.""" try: readHandle = open(_path, 'r') writeHandle = open(_path + ".tmp", 'w') for line in readHandle.readlines(): if line.startswith(CONTROL_IDENTIFIER): newline = line.split("=")[0] + "=" + str(value) writeHandle.write(newline) # You need this newline, otherwise the next line gets # overlapped here writeHandle.write("\n") else: writeHandle.write(line) readHandle.close() writeHandle.close() move(_path + ".tmp", _path) return True except: log.debug("Failed in populateValues() when operating on %s" % _path) return False def findConfig(self, configDir): """Take a configDir and find the configuration for the App.""" if configDir is None: return False # TODO: Do we need to take care of the vendor specific overrides ??? for configFile in listdir(configDir): if access(path.join(configDir, configFile), F_OK) is True: fn = path.join(configDir, configFile) self.configOptions[configFile.split(".")[0]] = fn else: pass def readConfig(self, key, configOptionsDict): """Take a key and dict and read the configurations for the App.""" self.tooltip = '' if key is None or configOptionsDict is None: return False try: fileHandle = open(configOptionsDict[key], 'r') except: return False for line in fileHandle.readlines(): if line.startswith(COMMENT_IDENTIFIER): self.tooltip = self.tooltip + line.lstrip(COMMENT_IDENTIFIER) elif line.startswith(CONTROL_IDENTIFIER): boolValue = line.split("=")[1] # Bloody boolValue could inherit the '\n' new line boolValue = boolValue.rstrip("\n") if boolValue == str(1) or "\"auto\"" in boolValue: self.configBool = True else: self.configBool = False # This will ensure that even if we don't read any string, tooltip # doesn't fail self.tooltip = self.tooltip + ''
def __init__(self, parent=None): ' Initialize QWidget inside MyMainWindow ' super(MyMainWindow, self).__init__(parent) self.statusBar().showMessage(__doc__.title()) self.setWindowTitle(__doc__) self.setMinimumSize(600, 800) self.setMaximumSize(2048, 1024) self.resize(1024, 800) self.setWindowIcon(QIcon.fromTheme("face-monkey")) if not A11Y: self.setStyleSheet('''QWidget{color:#fff;font-family:Oxygen} QWidget:item:hover, QWidget:item:selected { background-color: cyan; color: #000 } QWidget:disabled { color: #404040; background-color: #323232 } QWidget:focus { border: 1px solid cyan } QPushButton { background-color: gray; padding: 3px; border: 1px solid gray; border-radius: 9px; margin: 0;font-size: 12px; padding-left: 5px; padding-right: 5px } QLineEdit, QTextEdit { background-color: #4a4a4a; border: 1px solid gray; border-radius: 0; font-size: 12px; } QPushButton:pressed { background-color: #323232 } QComboBox { background-color: #4a4a4a; padding-left: 9px; border: 1px solid gray; border-radius: 5px; } QComboBox:pressed { background-color: gray } QComboBox QAbstractItemView, QMenu { border: 1px solid #4a4a4a; background:grey; selection-background-color: cyan; selection-color: #000; } QSlider { padding: 3px; font-size: 8px; padding-left: 2px; padding-right: 2px; border: 5px solid #1e1e1e } QSlider::sub-page:vertical { background-color: QLinearGradient(spread:pad, x1:0, y1:0, x2:1, y2:0.27, stop:0 rgba(255, 0, 0, 255), stop:1 rgba(50, 0, 0, 200)); border: 4px solid #1e1e1e; border-radius: 5px } QSlider::add-page:vertical { background-color: QLinearGradient(spread:pad, x1:0, y1:0, x2:1, y2:0.27, stop:0 rgba(0, 255, 0, 255), stop:1 rgba(0, 99, 0, 255)); border: 4px solid #1e1e1e; border-radius: 5px; } QSlider::handle:vertical { background-color: QLinearGradient(spread:pad, x1:0, y1:0, x2:1, y2:0.273, stop:0 rgba(0, 0, 0, 255), stop:1 gray); height: 5px; border: 1px dotted #fff; text-align: center; border-top-left-radius: 2px; border-bottom-left-radius: 2px; border-top-right-radius: 2px; border-bottom-right-radius 2px; margin-left: 2px; margin-right: 2px; } QSlider::handle:vertical:hover { border: 1px solid cyan } QSlider::sub-page:vertical:disabled { background: #bbb; border-color: #999; } QSlider::add-page:vertical:disabled { background: #eee; border-color: #999; } QSlider::handle:vertical:disabled { background: #eee; border: 1px solid #aaa; border-radius: 4px; } QToolBar, QStatusBar, QDockWidget::title{background-color:#323232;} QToolBar::handle, QToolBar::handle:vertical, QToolBar::handle:horizontal { border: 1px solid gray; border-radius: 9px; width: 19px; height: 19px; margin: 0.5px } QGroupBox { border: 1px solid gray; border-radius: 9px; padding-top: 9px; } QStatusBar, QToolBar::separator:horizontal, QToolBar::separator:vertical {color:gray} QScrollBar:vertical{ background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #212121,stop: 1.0 #323232); width: 10px; } QScrollBar:horizontal{ background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #212121,stop: 1.0 #323232); height: 10px; } QScrollBar::handle:vertical{ padding: 2px; min-height: 50px; background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #585858,stop: 1.0 #404040); border-radius: 5px; border: 1px solid #191919; } QScrollBar::handle:horizontal{ padding: 2px; min-width: 50px; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #585858,stop: 1.0 #404040); border-radius: 5px; border: 1px solid #191919; } QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical, QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical, QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal, QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal { background: none; border: none; } QDockWidget::close-button, QDockWidget::float-button { border: 1px solid gray; border-radius: 3px; background: darkgray; }''') self.process = QProcess() self.process.readyReadStandardOutput.connect(self.read_output) self.process.readyReadStandardError.connect(self.read_errors) self.process.finished.connect(self._process_finished) self.process.error.connect(self._process_finished) self.group0, self.group1 = QGroupBox("Options"), QGroupBox("Paths") self.group2 = QGroupBox("Nodes") self.group3 = QGroupBox("Python Code") self.group4, self.group5 = QGroupBox("Logs"), QGroupBox("Backend") g0grid, g1vlay = QGridLayout(self.group0), QVBoxLayout(self.group1) g5vlay = QVBoxLayout(self.group5) self.treeview_nodes, self.textedit_source = QTextEdit(), QTextEdit() self.dock1, self.dock2 = QDockWidget(), QDockWidget() self.output, self.dock3 = QTextEdit(), QDockWidget() self.treeview_nodes.setAutoFormatting(QTextEdit.AutoAll) self.treeview_nodes.setWordWrapMode(QTextOption.NoWrap) self.dock1.setWidget(self.treeview_nodes) self.dock2.setWidget(self.textedit_source) self.dock3.setWidget(self.output) self.dock1.setWindowTitle("Tree") self.dock2.setWindowTitle("Sources") self.dock3.setWindowTitle("STDOutput") featur = QDockWidget.DockWidgetMovable | QDockWidget.DockWidgetFloatable self.dock1.setFeatures(featur) self.dock2.setFeatures(featur) self.dock3.setFeatures(featur) QVBoxLayout(self.group2).addWidget(self.dock1) QVBoxLayout(self.group3).addWidget(self.dock2) QVBoxLayout(self.group4).addWidget(self.dock3) self.slider1, self.slider2 = QSlider(), QSlider() g0grid.addWidget(self.slider1, 0, 0) g0grid.addWidget(QLabel('Use Debug'), 0, 1) self.slider2.setValue(1) g0grid.addWidget(self.slider2, 1, 0) g0grid.addWidget(QLabel('Use verbose'), 1, 1) self.slider3, self.slider4 = QSlider(), QSlider() self.slider3.setValue(1) g0grid.addWidget(self.slider3, 2, 0) g0grid.addWidget(QLabel('Show compiling progress'), 2, 1) self.slider4.setValue(1) g0grid.addWidget(self.slider4, 3, 0) g0grid.addWidget(QLabel('Show Scons building debug'), 3, 1) self.slider5, self.slider6 = QSlider(), QSlider() g0grid.addWidget(self.slider5, 4, 0) g0grid.addWidget(QLabel('Keep debug unstriped binary'), 4, 1) g0grid.addWidget(self.slider6, 5, 0) g0grid.addWidget(QLabel('Traced execution outputs'), 5, 1) self.slider7, self.slider8 = QSlider(), QSlider() self.slider7.setValue(1) g0grid.addWidget(self.slider7, 6, 0) g0grid.addWidget(QLabel('Remove the build folder'), 6, 1) g0grid.addWidget(self.slider8, 7, 0) g0grid.addWidget(QLabel('No Python Optimizations'), 7, 1) self.slider9, self.slider10 = QSlider(), QSlider() g0grid.addWidget(self.slider9, 8, 0) g0grid.addWidget(QLabel('No Statements line numbers'), 8, 1) g0grid.addWidget(self.slider10, 9, 0) g0grid.addWidget(QLabel('Execute the output binary'), 9, 1) self.slider11, self.slider12 = QSlider(), QSlider() g0grid.addWidget(self.slider11, 10, 0) g0grid.addWidget(QLabel('Warning detected implicit exceptions'), 10, 1) g0grid.addWidget(self.slider12, 11, 0) g0grid.addWidget(QLabel('Keep the PYTHONPATH, do not Reset it'), 11, 1) self.slider13 = QSlider() g0grid.addWidget(self.slider13, 12, 0) g0grid.addWidget(QLabel('Enhance compile, CPython incompatible'), 12, 1) self.slider1a, self.slider2a = QSlider(), QSlider() g0grid.addWidget(self.slider1a, 0, 2) g0grid.addWidget(QLabel('Descendent Recursive Compile'), 0, 3) self.slider2a.setValue(1) g0grid.addWidget(self.slider2a, 1, 2) g0grid.addWidget(QLabel('Force non recursive compile'), 1, 3) self.slider3a, self.slider4a = QSlider(), QSlider() g0grid.addWidget(self.slider3a, 2, 2) g0grid.addWidget(QLabel('STD Lib Recursive Compile'), 2, 3) g0grid.addWidget(self.slider4a, 3, 2) g0grid.addWidget(QLabel('Enforce the use of Clang'), 3, 3) self.slider5a, self.slider6a = QSlider(), QSlider() self.slider5a.setValue(1) g0grid.addWidget(self.slider5a, 4, 2) g0grid.addWidget(QLabel('Use G++ link time optimizations'), 4, 3) g0grid.addWidget(self.slider6a, 5, 2) g0grid.addWidget(QLabel('Disable the console window'), 5, 3) self.slider7a, self.slider8a = QSlider(), QSlider() g0grid.addWidget(self.slider7a, 6, 2) g0grid.addWidget(QLabel('Force compile for MS Windows'), 6, 3) g0grid.addWidget(self.slider8a, 7, 2) g0grid.addWidget(QLabel('Use Python Debug versions'), 7, 3) self.slider9a, self.slider10a = QSlider(), QSlider() self.slider9a.setValue(1) g0grid.addWidget(self.slider9a, 8, 2) g0grid.addWidget(QLabel('Create standalone executable'), 8, 3) g0grid.addWidget(self.slider10a, 9, 2) g0grid.addWidget(QLabel('Enable Standalone mode build'), 9, 3) self.slider11a, self.slider12a = QSlider(), QSlider() g0grid.addWidget(self.slider11a, 10, 2) g0grid.addWidget(QLabel('Make module executable instead of app'), 10, 3) g0grid.addWidget(self.slider12a, 11, 2) g0grid.addWidget(QLabel('No froze module of stdlib as bytecode'), 11, 3) self.slider13a = QSlider() g0grid.addWidget(self.slider13a, 12, 2) g0grid.addWidget(QLabel('Force use of MinGW on MS Windows'), 12, 3) for each_widget in (self.slider1, self.slider2, self.slider3, self.slider4, self.slider5, self.slider6, self.slider7, self.slider8, self.slider9, self.slider10, self.slider11, self.slider12, self.slider13, self.slider1a, self.slider2a, self.slider3a, self.slider4a, self.slider5a, self.slider6a, self.slider7a, self.slider8a, self.slider9a, self.slider10a, self.slider11a, self.slider12a, self.slider13a): each_widget.setRange(0, 1) each_widget.setCursor(QCursor(Qt.OpenHandCursor)) each_widget.setTickInterval(1) each_widget.TickPosition(QSlider.TicksBothSides) self.combo1 = QComboBox() self.combo1.addItems(('2.7', '2.6', '3.2', '3.3')) g5vlay.addWidget(QLabel('Python Version')) g5vlay.addWidget(self.combo1) self.combo2 = QComboBox() self.combo2.addItems(('Default', 'Low', 'High')) g5vlay.addWidget(QLabel('CPU priority')) g5vlay.addWidget(self.combo2) self.combo3 = QComboBox() self.combo3.addItems(('1', '2', '3', '4', '5', '6', '7', '8', '9')) g5vlay.addWidget(QLabel('MultiProcessing Workers')) g5vlay.addWidget(self.combo3) self.outdir = QLineEdit() self.outdir.setStyleSheet("QLineEdit{margin-left:25px}") self.clearButton = QToolButton(self.outdir) self.clearButton.setIcon(QIcon.fromTheme("edit-clear")) self.clearButton.setIconSize(QSize(25, 25)) self.clearButton.setStyleSheet("QToolButton{border:none}") self.clearButton.hide() self.clearButton.clicked.connect(self.outdir.clear) self.outdir.textChanged.connect( lambda: self.clearButton.setVisible(True)) self.clearButton.clicked.connect( lambda: self.clearButton.setVisible(False)) self.outdir.setPlaceholderText('Output Directory') if path.isfile('.nuitka-output-dir.txt'): self.outdir.setText(open('.nuitka-output-dir.txt', 'r').read()) else: self.outdir.setText(path.expanduser("~")) self.completer, self.dirs = QCompleter(self), QDirModel(self) self.dirs.setFilter(QDir.Dirs | QDir.NoDotAndDotDot) self.completer.setModel(self.dirs) self.completer.setCaseSensitivity(Qt.CaseInsensitive) self.completer.setCompletionMode(QCompleter.PopupCompletion) self.completer.popup().setStyleSheet( """border:1px solid #4a4a4a;background:grey; selection-background-color:cyan;selection-color:#000""") self.completer.popup().setVerticalScrollBarPolicy( Qt.ScrollBarAlwaysOff) self.outdir.setCompleter(self.completer) self.btn1 = QPushButton(QIcon.fromTheme("document-open"), 'Open' if IS_WIN else '') self.btn1.clicked.connect( lambda: open('.nuitka-output-dir.txt', 'w').write( str( QFileDialog.getExistingDirectory( None, 'Open Output Directory', path.expanduser("~"))))) self.btn1.released.connect(lambda: self.outdir.setText( open('.nuitka-output-dir.txt', 'r').read())) g1vlay.addWidget(QLabel('Output Directory')) g1vlay.addWidget(self.outdir) g1vlay.addWidget(self.btn1) self.target = QLineEdit() self.target.setStyleSheet("QLineEdit{margin-left:25px}") self.clearButton2 = QToolButton(self.target) self.clearButton2.setIcon(QIcon.fromTheme("edit-clear")) self.clearButton2.setIconSize(QSize(25, 25)) self.clearButton2.setStyleSheet("QToolButton{border:none}") self.clearButton2.hide() self.clearButton2.clicked.connect(self.target.clear) self.target.textChanged.connect( lambda: self.clearButton2.setVisible(True)) self.clearButton2.clicked.connect( lambda: self.clearButton2.setVisible(False)) self.target.setPlaceholderText('Target Python App to Binary Compile') self.target.setCompleter(self.completer) self.btn2 = QPushButton(QIcon.fromTheme("document-open"), 'Open' if IS_WIN else '') self.btn2.clicked.connect(lambda: self.target.setText( str( QFileDialog.getOpenFileName( None, "Open", path.expanduser("~"), ';;'.join([ '{}(*.{})'.format(e.upper(), e) for e in ('py', 'pyw', '*') ]))))) g1vlay.addWidget(QLabel('Input File')) g1vlay.addWidget(self.target) g1vlay.addWidget(self.btn2) self.icon, self.icon_label = QLineEdit(), QLabel('Icon File') self.icon.setStyleSheet("QLineEdit{margin-left:25px}") self.clearButton3 = QToolButton(self.icon) self.clearButton3.setIcon(QIcon.fromTheme("edit-clear")) self.clearButton3.setIconSize(QSize(25, 25)) self.clearButton3.setStyleSheet("QToolButton{border:none}") self.clearButton3.hide() self.clearButton3.clicked.connect(self.icon.clear) self.icon.textChanged.connect( lambda: self.clearButton3.setVisible(True)) self.clearButton3.clicked.connect( lambda: self.clearButton3.setVisible(False)) self.icon.setPlaceholderText('Path to Icon file for your App') self.icon.setCompleter(self.completer) self.btn3 = QPushButton(QIcon.fromTheme("document-open"), 'Open' if IS_WIN else '') self.btn3.clicked.connect(lambda: self.icon.setText( str( QFileDialog.getOpenFileName( None, "Open", path.expanduser("~"), ';;'.join([ '{}(*.{})'.format(e.upper(), e) for e in ('ico', 'png', 'bmp', 'svg', '*') ]))))) g1vlay.addWidget(self.icon_label) g1vlay.addWidget(self.icon) g1vlay.addWidget(self.btn3) # Menu Bar inicialization and detail definitions menu_salir = QAction(QIcon.fromTheme("application-exit"), 'Quit', self) menu_salir.setStatusTip('Quit') menu_salir.triggered.connect(exit) menu_minimize = QAction(QIcon.fromTheme("go-down"), 'Minimize', self) menu_minimize.setStatusTip('Minimize') menu_minimize.triggered.connect(lambda: self.showMinimized()) menu_qt = QAction(QIcon.fromTheme("help-about"), 'About Qt', self) menu_qt.setStatusTip('About Qt...') menu_qt.triggered.connect(lambda: QMessageBox.aboutQt(self)) menu_dev = QAction(QIcon.fromTheme("applications-development"), 'Developer Manual PDF', self) menu_dev.setStatusTip('Open Nuitka Developer Manual PDF...') menu_dev.triggered.connect(lambda: call( OPEN + '/usr/share/doc/nuitka/Developer_Manual.pdf.gz', shell=True) ) menu_usr = QAction(QIcon.fromTheme("help-contents"), 'User Docs', self) menu_usr.setStatusTip('Open Nuitka End User Manual PDF...') menu_usr.triggered.connect(lambda: call( OPEN + '/usr/share/doc/nuitka/README.pdf.gz', shell=True)) menu_odoc = QAction(QIcon.fromTheme("help-browser"), 'OnLine Doc', self) menu_odoc.setStatusTip('Open Nuitka on line Documentation pages...') menu_odoc.triggered.connect( lambda: open_new_tab('http://nuitka.net/doc/user-manual.html')) menu_man = QAction(QIcon.fromTheme("utilities-terminal"), 'Man', self) menu_man.setStatusTip('Open Nuitka technical command line Man Pages..') menu_man.triggered.connect( lambda: call('xterm -e "man nuitka"', shell=True)) menu_tra = QAction(QIcon.fromTheme("applications-development"), 'View Nuitka-GUI Source Code', self) menu_tra.setStatusTip('View, study, edit Nuitka-GUI Libre Source Code') menu_tra.triggered.connect(lambda: call(OPEN + __file__, shell=True)) menu_foo = QAction(QIcon.fromTheme("folder"), 'Open Output Dir', self) menu_foo.setStatusTip('Open the actual Output Directory location...') menu_foo.triggered.connect( lambda: call(OPEN + str(self.outdir.text()), shell=True)) menu_pic = QAction(QIcon.fromTheme("camera-photo"), 'Screenshot', self) menu_pic.setStatusTip('Take a Screenshot for Documentation purposes..') menu_pic.triggered.connect( lambda: QPixmap.grabWindow(QApplication.desktop().winId()).save( QFileDialog.getSaveFileName(None, "Save", path.expanduser("~"), 'PNG(*.png)', 'png'))) menu_don = QAction(QIcon.fromTheme("emblem-favorite"), 'Help Nuitka', self) menu_don.setStatusTip('Help the Nuitka Open Source Libre Free Project') menu_don.triggered.connect( lambda: open_new_tab('http://nuitka.net/pages/donations.html')) # movable draggable toolbar self.toolbar = QToolBar(self) self.toolbar.setIconSize(QSize(16, 16)) self.toolbar.toggleViewAction().setText("Show/Hide Toolbar") l_spacer, r_spacer = QWidget(self), QWidget(self) l_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) r_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.toolbar.addWidget(l_spacer) self.toolbar.addSeparator() self.toolbar.addActions((menu_salir, menu_minimize, menu_qt, menu_odoc, menu_foo, menu_pic, menu_don)) if not IS_WIN: self.toolbar.addActions((menu_man, menu_dev, menu_tra, menu_usr)) self.toolbar.addSeparator() self.toolbar.addWidget(r_spacer) self.addToolBar(Qt.BottomToolBarArea, self.toolbar) # Bottom Buttons Bar self.buttonBox = QDialogButtonBox(self) self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Close) self.buttonBox.rejected.connect(exit) self.buttonBox.accepted.connect(self.run) self.guimode = QComboBox() self.guimode.addItems(('Full UX / UI', 'Simple UX / UI')) self.guimode.setStyleSheet( """QComboBox{background:transparent;border:0; margin-left:25px;color:gray;text-decoration:underline}""") self.guimode.currentIndexChanged.connect(self.set_guimode) container = QWidget() container_layout = QGridLayout(container) # Y, X container_layout.addWidget(self.guimode, 0, 1) container_layout.addWidget(self.group2, 1, 0) container_layout.addWidget(self.group3, 2, 0) container_layout.addWidget(self.group0, 1, 1) container_layout.addWidget(self.group1, 2, 1) container_layout.addWidget(self.group4, 1, 2) container_layout.addWidget(self.group5, 2, 2) container_layout.addWidget(self.buttonBox, 3, 1) self.setCentralWidget(container) # Paleta de colores para pintar transparente if not A11Y: palette = self.palette() palette.setBrush(QPalette.Base, Qt.transparent) self.setPalette(palette) self.setAttribute(Qt.WA_OpaquePaintEvent, False)
class XPopupWidget(QWidget): """ """ Direction = enum('North', 'South', 'East', 'West') Mode = enum('Popup', 'Dialog', 'ToolTip') Anchor = enum('TopLeft', 'TopCenter', 'TopRight', 'LeftTop', 'LeftCenter', 'LeftBottom', 'RightTop', 'RightCenter', 'RightBottom', 'BottomLeft', 'BottomCenter', 'BottomRight') aboutToShow = qt.Signal() accepted = qt.Signal() closed = qt.Signal() rejected = qt.Signal() resetRequested = qt.Signal() shown = qt.Signal() buttonClicked = qt.Signal(QAbstractButton) def __init__(self, parent=None, buttons=None): super(XPopupWidget, self).__init__(parent) # define custom properties self._anchor = XPopupWidget.Anchor.TopCenter self._autoCalculateAnchor = False self._autoCloseOnAccept = True self._autoCloseOnReject = True self._autoCloseOnFocusOut = False self._autoDefault = True self._first = True self._animated = False self._currentMode = None self._positionLinkedTo = [] # define controls self._resizable = True self._popupPadding = 10 self._titleBarVisible = True self._buttonBoxVisible = True self._dialogButton = QToolButton(self) self._closeButton = QToolButton(self) self._scrollArea = QScrollArea(self) self._sizeGrip = QSizeGrip(self) self._sizeGrip.setFixedWidth(12) self._sizeGrip.setFixedHeight(12) self._leftSizeGrip = QSizeGrip(self) self._leftSizeGrip.setFixedWidth(12) self._leftSizeGrip.setFixedHeight(12) if buttons is None: buttons = QDialogButtonBox.NoButton self._buttonBox = QDialogButtonBox(buttons, Qt.Horizontal, self) self._buttonBox.setContentsMargins(3, 0, 3, 9) self._scrollArea.setWidgetResizable(True) self._scrollArea.setFrameShape(QScrollArea.NoFrame) self._scrollArea.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) palette = self.palette() self._scrollArea.setPalette(palette) self._dialogButton.setToolTip('Popout to Dialog') self._closeButton.setToolTip('Close Popup') for btn in (self._dialogButton, self._closeButton): btn.setAutoRaise(True) btn.setIconSize(QSize(14, 14)) btn.setMaximumSize(16, 16) # setup the icons icon = QIcon(projexui.resources.find('img/dialog.png')) self._dialogButton.setIcon(icon) icon = QIcon(projexui.resources.find('img/close.png')) self._closeButton.setIcon(icon) # define the ui hlayout = QHBoxLayout() hlayout.setSpacing(0) hlayout.addStretch(1) hlayout.addWidget(self._dialogButton) hlayout.addWidget(self._closeButton) hlayout.setContentsMargins(0, 0, 0, 0) hlayout2 = QHBoxLayout() hlayout2.addWidget(self._buttonBox) hlayout2.setContentsMargins(0, 0, 3, 0) vlayout = QVBoxLayout() vlayout.addLayout(hlayout) vlayout.addWidget(self._scrollArea) vlayout.addLayout(hlayout2) vlayout.setContentsMargins(3, 2, 3, 2) vlayout.setSpacing(0) self.setLayout(vlayout) self.setPositionLinkedTo(parent) # set default properties self.setAutoFillBackground(True) self.setBackgroundRole(QPalette.Button) self.setWindowTitle('Popup') self.setFocusPolicy(Qt.StrongFocus) self.setCurrentMode(XPopupWidget.Mode.Popup) # create connections self._dialogButton.clicked.connect(self.setDialogMode) self._closeButton.clicked.connect(self.reject) self._buttonBox.accepted.connect(self.accept) self._buttonBox.rejected.connect(self.reject) self._buttonBox.clicked.connect(self.handleButtonClick) def addButton(self, button, role=QDialogButtonBox.ActionRole): """ Adds a custom button to the button box for this popup widget. :param button | <QAbstractButton> || <str> :return <button> || None (based on if a button or string was given) """ return self._buttonBox.addButton(button, role) def adjustContentsMargins(self): """ Adjusts the contents for this widget based on the anchor and \ mode. """ anchor = self.anchor() mode = self.currentMode() # margins for a dialog if (mode == XPopupWidget.Mode.Dialog): self.setContentsMargins(0, 0, 0, 0) # margins for a top anchor point elif (anchor & (XPopupWidget.Anchor.TopLeft | XPopupWidget.Anchor.TopCenter | XPopupWidget.Anchor.TopRight)): self.setContentsMargins(0, self.popupPadding() + 5, 0, 0) # margins for a bottom anchor point elif ( anchor & (XPopupWidget.Anchor.BottomLeft | XPopupWidget.Anchor.BottomCenter | XPopupWidget.Anchor.BottomRight)): self.setContentsMargins(0, 0, 0, self.popupPadding()) # margins for a left anchor point elif (anchor & (XPopupWidget.Anchor.LeftTop | XPopupWidget.Anchor.LeftCenter | XPopupWidget.Anchor.LeftBottom)): self.setContentsMargins(self.popupPadding(), 0, 0, 0) # margins for a right anchor point else: self.setContentsMargins(0, 0, self.popupPadding(), 0) self.adjustMask() def adjustMask(self): """ Updates the alpha mask for this popup widget. """ if self.currentMode() == XPopupWidget.Mode.Dialog: self.clearMask() return path = self.borderPath() bitmap = QBitmap(self.width(), self.height()) bitmap.fill(QColor('white')) painter = QPainter() painter.begin(bitmap) painter.setRenderHint(QPainter.Antialiasing) pen = QPen(QColor('black')) pen.setWidthF(0.75) painter.setPen(pen) painter.setBrush(QColor('black')) painter.drawPath(path) painter.end() self.setMask(bitmap) def adjustSize(self): """ Adjusts the size of this popup to best fit the new widget size. """ widget = self.centralWidget() if widget is None: super(XPopupWidget, self).adjustSize() return widget.adjustSize() hint = widget.minimumSizeHint() size = widget.minimumSize() width = max(size.width(), hint.width()) height = max(size.height(), hint.height()) width += 20 height += 20 if self._buttonBoxVisible: height += self.buttonBox().height() + 10 if self._titleBarVisible: height += max(self._dialogButton.height(), self._closeButton.height()) + 10 curr_w = self.width() curr_h = self.height() # determine if we need to move based on our anchor anchor = self.anchor() if anchor & (self.Anchor.LeftBottom | self.Anchor.RightBottom | \ self.Anchor.BottomLeft | self.Anchor.BottomCenter | \ self.Anchor.BottomRight): delta_y = height - curr_h elif anchor & (self.Anchor.LeftCenter | self.Anchor.RightCenter): delta_y = (height - curr_h) / 2 else: delta_y = 0 if anchor & (self.Anchor.RightTop | self.Anchor.RightCenter | \ self.Anchor.RightTop | self.Anchor.TopRight): delta_x = width - curr_w elif anchor & (self.Anchor.TopCenter | self.Anchor.BottomCenter): delta_x = (width - curr_w) / 2 else: delta_x = 0 self.setMinimumSize(width, height) self.resize(width, height) pos = self.pos() pos.setX(pos.x() - delta_x) pos.setY(pos.y() - delta_y) self.move(pos) @qt.Slot() def accept(self): """ Emits the accepted signal and closes the popup. """ if not self.signalsBlocked(): self.accepted.emit() if self.autoCloseOnAccept(): self.close() def anchor(self): """ Returns the anchor point for this popup widget. :return <XPopupWidget.Anchor> """ return self._anchor def autoCalculateAnchor(self): """ Returns whether or not this popup should calculate the anchor point on popup based on the parent widget and the popup point. :return <bool> """ return self._autoCalculateAnchor def autoCloseOnAccept(self): """ Returns whether or not this popup widget manages its own close on accept behavior. :return <bool> """ return self._autoCloseOnAccept def autoCloseOnReject(self): """ Returns whether or not this popup widget manages its own close on reject behavior. :return <bool> """ return self._autoCloseOnReject def autoCloseOnFocusOut(self): """ Returns whether or not this popup widget should auto-close when the user clicks off the view. :return <bool> """ return self._autoCloseOnFocusOut def autoDefault(self): """ Returns whether or not clicking enter should default to the accept key. :return <bool> """ return self._autoDefault def borderPath(self): """ Returns the border path that will be drawn for this widget. :return <QPainterPath> """ path = QPainterPath() x = 1 y = 1 w = self.width() - 2 h = self.height() - 2 pad = self.popupPadding() anchor = self.anchor() # create a path for a top-center based popup if anchor == XPopupWidget.Anchor.TopCenter: path.moveTo(x, y + pad) path.lineTo(x + ((w / 2) - pad), y + pad) path.lineTo(x + (w / 2), y) path.lineTo(x + ((w / 2) + pad), y + pad) path.lineTo(x + w, y + pad) path.lineTo(x + w, y + h) path.lineTo(x, y + h) path.lineTo(x, y + pad) # create a path for a top-left based popup elif anchor == XPopupWidget.Anchor.TopLeft: path.moveTo(x, y + pad) path.lineTo(x + pad, y) path.lineTo(x + 2 * pad, y + pad) path.lineTo(x + w, y + pad) path.lineTo(x + w, y + h) path.lineTo(x, y + h) path.lineTo(x, y + pad) # create a path for a top-right based popup elif anchor == XPopupWidget.Anchor.TopRight: path.moveTo(x, y + pad) path.lineTo(x + w - 2 * pad, y + pad) path.lineTo(x + w - pad, y) path.lineTo(x + w, y + pad) path.lineTo(x + w, y + h) path.lineTo(x, y + h) path.lineTo(x, y + pad) # create a path for a bottom-left based popup elif anchor == XPopupWidget.Anchor.BottomLeft: path.moveTo(x, y) path.lineTo(x + w, y) path.lineTo(x + w, y + h - pad) path.lineTo(x + 2 * pad, y + h - pad) path.lineTo(x + pad, y + h) path.lineTo(x, y + h - pad) path.lineTo(x, y) # create a path for a south based popup elif anchor == XPopupWidget.Anchor.BottomCenter: path.moveTo(x, y) path.lineTo(x + w, y) path.lineTo(x + w, y + h - pad) path.lineTo(x + ((w / 2) + pad), y + h - pad) path.lineTo(x + (w / 2), y + h) path.lineTo(x + ((w / 2) - pad), y + h - pad) path.lineTo(x, y + h - pad) path.lineTo(x, y) # create a path for a bottom-right based popup elif anchor == XPopupWidget.Anchor.BottomRight: path.moveTo(x, y) path.lineTo(x + w, y) path.lineTo(x + w, y + h - pad) path.lineTo(x + w - pad, y + h) path.lineTo(x + w - 2 * pad, y + h - pad) path.lineTo(x, y + h - pad) path.lineTo(x, y) # create a path for a right-top based popup elif anchor == XPopupWidget.Anchor.RightTop: path.moveTo(x, y) path.lineTo(x + w - pad, y) path.lineTo(x + w, y + pad) path.lineTo(x + w - pad, y + 2 * pad) path.lineTo(x + w - pad, y + h) path.lineTo(x, y + h) path.lineTo(x, y) # create a path for a right-center based popup elif anchor == XPopupWidget.Anchor.RightCenter: path.moveTo(x, y) path.lineTo(x + w - pad, y) path.lineTo(x + w - pad, y + ((h / 2) - pad)) path.lineTo(x + w, y + (h / 2)) path.lineTo(x + w - pad, y + ((h / 2) + pad)) path.lineTo(x + w - pad, y + h) path.lineTo(x, y + h) path.lineTo(x, y) # create a path for a right-bottom based popup elif anchor == XPopupWidget.Anchor.RightBottom: path.moveTo(x, y) path.lineTo(x + w - pad, y) path.lineTo(x + w - pad, y + h - 2 * pad) path.lineTo(x + w, y + h - pad) path.lineTo(x + w - pad, y + h) path.lineTo(x, y + h) path.lineTo(x, y) # create a path for a left-top based popup elif anchor == XPopupWidget.Anchor.LeftTop: path.moveTo(x + pad, y) path.lineTo(x + w, y) path.lineTo(x + w, y + h) path.lineTo(x + pad, y + h) path.lineTo(x + pad, y + 2 * pad) path.lineTo(x, y + pad) path.lineTo(x + pad, y) # create a path for an left-center based popup elif anchor == XPopupWidget.Anchor.LeftCenter: path.moveTo(x + pad, y) path.lineTo(x + w, y) path.lineTo(x + w, y + h) path.lineTo(x + pad, y + h) path.lineTo(x + pad, y + ((h / 2) + pad)) path.lineTo(x, y + (h / 2)) path.lineTo(x + pad, y + ((h / 2) - pad)) path.lineTo(x + pad, y) # create a path for a left-bottom based popup elif anchor == XPopupWidget.Anchor.LeftBottom: path.moveTo(x + pad, y) path.lineTo(x + w, y) path.lineTo(x + w, y + h) path.lineTo(x + pad, y + h) path.lineTo(x, y + h - pad) path.lineTo(x + pad, y + h - 2 * pad) path.lineTo(x + pad, y) return path def buttonBox(self): """ Returns the button box that is used to control this popup widget. :return <QDialogButtonBox> """ return self._buttonBox def centralWidget(self): """ Returns the central widget that is being used by this popup. :return <QWidget> """ return self._scrollArea.widget() def close(self): """ Closes the popup widget and central widget. """ widget = self.centralWidget() if widget and not widget.close(): return super(XPopupWidget, self).close() def closeEvent(self, event): widget = self.centralWidget() if widget and not widget.close() and \ self.currentMode() != XPopupWidget.Mode.ToolTip: event.ignore() else: super(XPopupWidget, self).closeEvent(event) self.closed.emit() def currentMode(self): """ Returns the current mode for this widget. :return <XPopupWidget.Mode> """ return self._currentMode @deprecatedmethod('XPopupWidget', 'Direction is no longer used, use anchor instead') def direction(self): """ Returns the current direction parameter for this widget. :return <XPopupWidget.Direction> """ anchor = self.anchor() if (anchor & (XPopupWidget.Anchor.TopLeft | XPopupWidget.Anchor.TopCenter | XPopupWidget.Anchor.TopRight)): return XPopupWidget.Direction.North elif ( anchor & (XPopupWidget.Anchor.BottomLeft | XPopupWidget.Anchor.BottomCenter | XPopupWidget.Anchor.BottomRight)): return XPopupWidget.Direction.South elif (anchor & (XPopupWidget.Anchor.LeftTop | XPopupWidget.Anchor.LeftCenter | XPopupWidget.Anchor.LeftBottom)): return XPopupWidget.Direction.East else: return XPopupWidget.Direction.West def eventFilter(self, object, event): """ Processes when the window is moving to update the position for the popup if in popup mode. :param object | <QObject> event | <QEvent> """ links = self.positionLinkedTo() is_dialog = self.currentMode() == self.Mode.Dialog if object not in links: return False if event.type() == event.Close: self.close() return False if event.type() == event.Hide and not is_dialog: self.hide() return False if event.type() == event.Move and not is_dialog: deltaPos = event.pos() - event.oldPos() self.move(self.pos() + deltaPos) return False if self.currentMode() != self.Mode.ToolTip: return False if event.type() == event.Leave: pos = object.mapFromGlobal(QCursor.pos()) if (not object.rect().contains(pos)): self.close() event.accept() return True if event.type() in (event.MouseButtonPress, event.MouseButtonDblClick): self.close() event.accept() return True return False @qt.Slot(QAbstractButton) def handleButtonClick(self, button): """ Handles the button click for this widget. If the Reset button was clicked, then the resetRequested signal will be emitted. All buttons will emit the buttonClicked signal. :param button | <QAbstractButton> """ if (self.signalsBlocked()): return if (button == self._buttonBox.button(QDialogButtonBox.Reset)): self.resetRequested.emit() self.buttonClicked.emit(button) def isAnimated(self): """ Returns whether or not the popup widget should animate its opacity when it is shown. :return <bool> """ return self._animated def isResizable(self): """ Returns if this popup is resizable or not. :return <bool> """ return self._resizable def keyPressEvent(self, event): """ Looks for the Esc key to close the popup. :param event | <QKeyEvent> """ if (event.key() == Qt.Key_Escape): self.reject() event.accept() return elif (event.key() in (Qt.Key_Return, Qt.Key_Enter)): if self._autoDefault: self.accept() event.accept() return super(XPopupWidget, self).keyPressEvent(event) def mapAnchorFrom(self, widget, globalPos): """ Returns the anchor point that best fits within the given widget from the inputed global position. :param widget | <QWidget> globalPos | <QPoint> :return <XPopupWidget.Anchor> """ localPos = widget.mapFromGlobal(globalPos) x = localPos.x() y = localPos.y() w = widget.width() h = widget.height() cw = self.width() / 2 ch = self.height() / 2 # by default, try to do a center point, so make sure the center point # is at least 1/2 the width longer from each edge if x < cw and h - y < ch: return XPopupWidget.Anchor.BottomLeft elif x < cw: return XPopupWidget.Anchor.TopLeft elif w - x < cw and h - y < ch: return XPopupWidget.Anchor.BottomRight elif w - x < cw: return XPopupWidget.Anchor.TopRight elif h - y < ch: return XPopupWidget.Anchor.BottomCenter else: return XPopupWidget.Anchor.TopCenter def popup(self, pos=None): """ Pops up this widget at the inputed position. The inputed point should \ be in global space. :param pos | <QPoint> :return <bool> success """ if self._first and self.centralWidget() is not None: self.adjustSize() self._first = False if not self.signalsBlocked(): self.aboutToShow.emit() if not pos: pos = QCursor.pos() if self.currentMode() == XPopupWidget.Mode.Dialog and \ self.isVisible(): return False elif self.currentMode() == XPopupWidget.Mode.Dialog: self.setPopupMode() # auto-calculate the point if self.autoCalculateAnchor(): self.setAnchor(self.mapAnchorFrom(self.parent(), pos)) pad = self.popupPadding() # determine where to move based on the anchor anchor = self.anchor() # MODIFY X POSITION # align x-left if (anchor & (XPopupWidget.Anchor.TopLeft | XPopupWidget.Anchor.BottomLeft)): pos.setX(pos.x() - pad) # align x-center elif (anchor & (XPopupWidget.Anchor.TopCenter | XPopupWidget.Anchor.BottomCenter)): pos.setX(pos.x() - self.width() / 2) # align x-right elif ( anchor & (XPopupWidget.Anchor.TopRight | XPopupWidget.Anchor.BottomRight)): pos.setX(pos.x() - self.width() + pad) # align x-padded elif (anchor & (XPopupWidget.Anchor.RightTop | XPopupWidget.Anchor.RightCenter | XPopupWidget.Anchor.RightBottom)): pos.setX(pos.x() - self.width()) # MODIFY Y POSITION # align y-top if (anchor & (XPopupWidget.Anchor.LeftTop | XPopupWidget.Anchor.RightTop)): pos.setY(pos.y() - pad) # align y-center elif (anchor & (XPopupWidget.Anchor.LeftCenter | XPopupWidget.Anchor.RightCenter)): pos.setY(pos.y() - self.height() / 2) # align y-bottom elif (anchor & (XPopupWidget.Anchor.LeftBottom | XPopupWidget.Anchor.RightBottom)): pos.setY(pos.y() - self.height() + pad) # align y-padded elif ( anchor & (XPopupWidget.Anchor.BottomLeft | XPopupWidget.Anchor.BottomCenter | XPopupWidget.Anchor.BottomRight)): pos.setY(pos.y() - self.height()) self.adjustMask() self.move(pos) self.update() self.setUpdatesEnabled(True) if self.isAnimated(): anim = QPropertyAnimation(self, 'windowOpacity') anim.setParent(self) anim.setStartValue(0.0) anim.setEndValue(self.windowOpacity()) anim.setDuration(500) anim.finished.connect(anim.deleteLater) self.setWindowOpacity(0.0) else: anim = None self.show() if self.currentMode() != XPopupWidget.Mode.ToolTip: self.activateWindow() widget = self.centralWidget() if widget: self.centralWidget().setFocus() if anim: anim.start() if not self.signalsBlocked(): self.shown.emit() return True def paintEvent(self, event): """ Overloads the paint event to handle painting pointers for the popup \ mode. :param event | <QPaintEvent> """ # use the base technique for the dialog mode if self.currentMode() == XPopupWidget.Mode.Dialog: super(XPopupWidget, self).paintEvent(event) return # setup the coloring options palette = self.palette() painter = QPainter() painter.begin(self) pen = QPen(palette.color(palette.Window).darker(130)) pen.setWidthF(1.75) painter.setPen(pen) painter.setRenderHint(painter.Antialiasing) painter.setBrush(palette.color(palette.Window)) painter.drawPath(self.borderPath()) painter.end() def popupPadding(self): """ Returns the amount of pixels to pad the popup arrow for this widget. :return <int> """ return self._popupPadding def positionLinkedTo(self): """ Returns the widget that this popup is linked to for positional changes. :return [<QWidget>, ..] """ return self._positionLinkedTo @qt.Slot() def reject(self): """ Emits the accepted signal and closes the popup. """ if not self.signalsBlocked(): self.rejected.emit() if self.autoCloseOnReject(): self.close() def resizeEvent(self, event): """ Resizes this widget and updates the mask. :param event | <QResizeEvent> """ self.setUpdatesEnabled(False) super(XPopupWidget, self).resizeEvent(event) self.adjustMask() self.setUpdatesEnabled(True) x = self.width() - self._sizeGrip.width() y = self.height() - self._sizeGrip.height() self._leftSizeGrip.move(0, y) self._sizeGrip.move(x, y) def scrollArea(self): """ Returns the scroll area widget for this popup. :return <QScrollArea> """ return self._scrollArea def setAnimated(self, state): """ Sets whether or not the popup widget should animate its opacity when it is shown. :param state | <bool> """ self._animated = state self.setAttribute(Qt.WA_TranslucentBackground, state) def setAutoCloseOnAccept(self, state): """ Sets whether or not the popup handles closing for accepting states. :param state | <bool> """ self._autoCloseOnAccept = state def setAutoCloseOnReject(self, state): """ Sets whether or not the popup handles closing for rejecting states. :param state | <bool> """ self._autoCloseOnReject = state def setAutoDefault(self, state): """ Sets whether or not the buttons should respond to defaulting options when the user is interacting with it. :param state | <bool> """ self._autoDefault = state for button in self.buttonBox().buttons(): button.setAutoDefault(state) button.setDefault(state) def setAnchor(self, anchor): """ Sets the anchor position for this popup widget to the inputed point. :param anchor | <XPopupWidget.Anchor> """ self._anchor = anchor self.adjustContentsMargins() def setAutoCalculateAnchor(self, state): """ Sets whether or not this widget should auto-calculate the anchor point based on the parent position when the popup is triggered. :param state | <bool> """ self._autoCalculateAnchor = state def setAutoCloseOnFocusOut(self, state): """ Sets whether or not this popup widget should auto-close when the user clicks off the view. :param state | <bool> """ self._autoCloseOnFocusOut = state self.updateModeSettings() def setCentralWidget(self, widget): """ Sets the central widget that will be used by this popup. :param widget | <QWidget> || None """ self._scrollArea.takeWidget() self._scrollArea.setWidget(widget) self.adjustSize() def setCurrentMode(self, mode): """ Sets the current mode for this dialog to the inputed mode. :param mode | <XPopupWidget.Mode> """ if (self._currentMode == mode): return self._currentMode = mode self.updateModeSettings() @qt.Slot() def setDialogMode(self): """ Sets the current mode value to Dialog. """ self.setCurrentMode(XPopupWidget.Mode.Dialog) @deprecatedmethod('XPopupWidget', 'Direction is no longer used, use setAnchor instead') def setDirection(self, direction): """ Sets the direction for this widget to the inputed direction. :param direction | <XPopupWidget.Direction> """ if (direction == XPopupWidget.Direction.North): self.setAnchor(XPopupWidget.Anchor.TopCenter) elif (direction == XPopupWidget.Direction.South): self.setAnchor(XPopupWidget.Anchor.BottomCenter) elif (direction == XPopupWidget.Direction.East): self.setAnchor(XPopupWidget.Anchor.LeftCenter) else: self.setAnchor(XPopupWidget.Anchor.RightCenter) def setPalette(self, palette): """ Sets the palette for this widget and the scroll area. :param palette | <QPalette> """ super(XPopupWidget, self).setPalette(palette) self._scrollArea.setPalette(palette) def setPopupMode(self): """ Sets the current mode value to Popup. """ self.setCurrentMode(XPopupWidget.Mode.Popup) def setPopupPadding(self, padding): """ Sets the amount to pad the popup area when displaying this widget. :param padding | <int> """ self._popupPadding = padding self.adjustContentsMargins() def setPositionLinkedTo(self, widgets): """ Sets the widget that this popup will be linked to for positional changes. :param widgets | <QWidget> || [<QWidget>, ..] """ if type(widgets) in (list, set, tuple): new_widgets = list(widgets) else: new_widgets = [] widget = widgets while widget: widget.installEventFilter(self) new_widgets.append(widget) widget = widget.parent() self._positionLinkedTo = new_widgets def setResizable(self, state): self._resizable = state self._sizeGrip.setVisible(state) self._leftSizeGrip.setVisible(state) def setShowButtonBox(self, state): self._buttonBoxVisible = state self.buttonBox().setVisible(state) def setShowTitleBar(self, state): self._titleBarVisible = state self._dialogButton.setVisible(state) self._closeButton.setVisible(state) def setToolTipMode(self): """ Sets the mode for this popup widget to ToolTip """ self.setCurrentMode(XPopupWidget.Mode.ToolTip) def setVisible(self, state): super(XPopupWidget, self).setVisible(state) widget = self.centralWidget() if widget: widget.setVisible(state) def timerEvent(self, event): """ When the timer finishes, hide the tooltip popup widget. :param event | <QEvent> """ if self.currentMode() == XPopupWidget.Mode.ToolTip: self.killTimer(event.timerId()) event.accept() self.close() else: super(XPopupWidget, self).timerEvent(event) def updateModeSettings(self): mode = self.currentMode() is_visible = self.isVisible() # display as a floating dialog if mode == XPopupWidget.Mode.Dialog: self.setWindowFlags(Qt.Dialog | Qt.Tool) self.setAttribute(Qt.WA_TransparentForMouseEvents, False) self._closeButton.setVisible(False) self._dialogButton.setVisible(False) # display as a user tooltip elif mode == XPopupWidget.Mode.ToolTip: flags = Qt.Popup | Qt.FramelessWindowHint self.setWindowFlags(flags) self.setBackgroundRole(QPalette.Window) self.setAttribute(Qt.WA_TransparentForMouseEvents) self.setShowTitleBar(False) self.setShowButtonBox(False) self.setFocusPolicy(Qt.NoFocus) # hide the scrollbars policy = Qt.ScrollBarAlwaysOff self._scrollArea.setVerticalScrollBarPolicy(policy) self._scrollArea.setHorizontalScrollBarPolicy(policy) # display as a popup widget else: flags = Qt.Popup | Qt.FramelessWindowHint if not self.autoCloseOnFocusOut(): flags |= Qt.Tool self.setWindowFlags(flags) self._closeButton.setVisible(self._titleBarVisible) self._dialogButton.setVisible(self._titleBarVisible) self.setBackgroundRole(QPalette.Button) self.adjustContentsMargins() if (is_visible): self.show() @staticmethod @deprecatedmethod('XPopupWidget', 'This method no longer has an effect as we are not '\ 'storing references to the tooltip.') def hideToolTip(key=None): """ Hides any existing tooltip popup widgets. :warning This method is deprecated! """ pass @staticmethod def showToolTip(text, point=None, anchor=None, parent=None, background=None, foreground=None, key=None, seconds=5): """ Displays a popup widget as a tooltip bubble. :param text | <str> point | <QPoint> || None anchor | <XPopupWidget.Mode.Anchor> || None parent | <QWidget> || None background | <QColor> || None foreground | <QColor> || None key | <str> || None seconds | <int> """ if point is None: point = QCursor.pos() if parent is None: parent = QApplication.activeWindow() if anchor is None and parent is None: anchor = XPopupWidget.Anchor.TopCenter # create a new tooltip widget widget = XPopupWidget(parent) widget.setToolTipMode() widget.setResizable(False) # create the tooltip label label = QLabel(text, widget) label.setOpenExternalLinks(True) label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) label.setMargin(3) label.setIndent(3) label.adjustSize() widget.setCentralWidget(label) # update the tip label.adjustSize() widget.adjustSize() palette = widget.palette() if not background: background = palette.color(palette.ToolTipBase) if not foreground: foreground = palette.color(palette.ToolTipText) palette.setColor(palette.Window, QColor(background)) palette.setColor(palette.WindowText, QColor(foreground)) widget.setPalette(palette) widget.centralWidget().setPalette(palette) if anchor is None: widget.setAutoCalculateAnchor(True) else: widget.setAnchor(anchor) widget.setAutoCloseOnFocusOut(True) widget.setAttribute(Qt.WA_DeleteOnClose) widget.popup(point) widget.startTimer(1000 * seconds) return widget
class DeletionOptions(QDialog): def __init__(self, parent, model): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint QDialog.__init__(self, parent, flags) self.model = model self._setupUi() self.model.view = self self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) def _setupUi(self): self.setWindowTitle(tr("Deletion Options")) self.resize(400, 270) self.verticalLayout = QVBoxLayout(self) self.msgLabel = QLabel() self.verticalLayout.addWidget(self.msgLabel) self.linkCheckbox = QCheckBox(tr("Link deleted files")) self.verticalLayout.addWidget(self.linkCheckbox) text = tr( "After having deleted a duplicate, place a link targeting the reference file " "to replace the deleted file.") self.linkMessageLabel = QLabel(text) self.linkMessageLabel.setWordWrap(True) self.verticalLayout.addWidget(self.linkMessageLabel) self.linkTypeRadio = RadioBox(items=[tr("Symlink"), tr("Hardlink")], spread=False) self.verticalLayout.addWidget(self.linkTypeRadio) if not self.model.supports_links(): self.linkCheckbox.setEnabled(False) self.linkTypeRadio.setEnabled(False) self.linkCheckbox.setText(self.linkCheckbox.text() + tr(" (unsupported)")) self.directCheckbox = QCheckBox(tr("Directly delete files")) self.verticalLayout.addWidget(self.directCheckbox) text = tr( "Instead of sending files to trash, delete them directly. This option is usually " "used as a workaround when the normal deletion method doesn't work." ) self.directMessageLabel = QLabel(text) self.directMessageLabel.setWordWrap(True) self.verticalLayout.addWidget(self.directMessageLabel) self.buttonBox = QDialogButtonBox() self.buttonBox.addButton(tr("Proceed"), QDialogButtonBox.AcceptRole) self.buttonBox.addButton(tr("Cancel"), QDialogButtonBox.RejectRole) self.verticalLayout.addWidget(self.buttonBox) #--- model --> view def update_msg(self, msg): self.msgLabel.setText(msg) def show(self): self.linkCheckbox.setChecked(self.model.link_deleted) self.linkTypeRadio.selected_index = 1 if self.model.use_hardlinks else 0 self.directCheckbox.setChecked(self.model.direct) result = self.exec() self.model.link_deleted = self.linkCheckbox.isChecked() self.model.use_hardlinks = self.linkTypeRadio.selected_index == 1 self.model.direct = self.directCheckbox.isChecked() return result == QDialog.Accepted
def setupUi(self): if self.paramType == GPFModelerParameterDefinitionDialog.PARAMETER_BANDS or \ isinstance(self.param, ParameterBands): self.setWindowTitle(self.tr('Parameter definition')) self.verticalLayout = QVBoxLayout(self) self.verticalLayout.setSpacing(40) self.verticalLayout.setMargin(20) self.horizontalLayoutName = QHBoxLayout(self) self.horizontalLayoutName.setSpacing(2) self.horizontalLayoutName.setMargin(0) self.label = QLabel(self.tr('Parameter name')) self.horizontalLayoutName.addWidget(self.label) self.nameTextBox = QLineEdit() self.horizontalLayoutName.addWidget(self.nameTextBox) self.verticalLayout.addLayout(self.horizontalLayoutName) self.horizontalLayoutRequired = QHBoxLayout(self) self.horizontalLayoutRequired.setSpacing(2) self.horizontalLayoutRequired.setMargin(0) self.horizontalLayoutParent = QHBoxLayout(self) self.horizontalLayoutParent.setSpacing(2) self.horizontalLayoutParent.setMargin(0) self.horizontalLayoutDefault = QHBoxLayout(self) self.horizontalLayoutDefault.setSpacing(2) self.horizontalLayoutDefault.setMargin(0) self.horizontalLayoutDatatype = QHBoxLayout(self) self.horizontalLayoutDatatype.setSpacing(2) self.horizontalLayoutDatatype.setMargin(0) if isinstance(self.param, Parameter): self.nameTextBox.setText(self.param.description) self.horizontalLayoutDefault.addWidget(QLabel(self.tr('Default band'))) self.defaultTextBox = QLineEdit() if self.param is not None: self.defaultTextBox.setText(self.param.default) self.horizontalLayoutDefault.addWidget(self.defaultTextBox) self.verticalLayout.addLayout(self.horizontalLayoutDefault) self.horizontalLayoutDefault.addWidget(QLabel(self.tr('Raster layer'))) self.parentCombo = QComboBox() idx = 0 for param in self.alg.inputs.values(): if isinstance(param.param, (ParameterRaster)): self.parentCombo.addItem(param.param.description, param.param.name) if self.param is not None: if self.param.bandSourceRaster == param.param.name: self.parentCombo.setCurrentIndex(idx) idx += 1 self.horizontalLayoutDefault.addWidget(self.parentCombo) self.verticalLayout.addLayout(self.horizontalLayoutDefault) self.horizontalLayoutRequired.addWidget(QLabel(self.tr('Required'))) self.yesNoCombo = QComboBox() self.yesNoCombo.addItem(self.tr('Yes')) self.yesNoCombo.addItem(self.tr('No')) self.horizontalLayoutRequired.addWidget(self.yesNoCombo) if self.param is not None: self.yesNoCombo.setCurrentIndex( 1 if self.param.optional else 0) self.verticalLayout.addLayout(self.horizontalLayoutRequired) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.buttonBox.setObjectName('buttonBox') self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) self.verticalLayout.addWidget(self.buttonBox) self.setLayout(self.verticalLayout) else: ModelerParameterDefinitionDialog.setupUi(self)
class NumberFormatDlg(QDialog): changed = Signal() def __init__(self, format, parent=None): super(NumberFormatDlg, self).__init__(parent) self.setAttribute(Qt.WA_DeleteOnClose) self.format = format self.create_widgets() self.layout_widgets() self.create_connections() self.setWindowTitle("Set Number Format (Modeless)") def create_widgets(self): punctuationRe = QRegExp(r"[ ,;:.]") self.thousandsLabel = QLabel("&Thousands separator") self.thousandsEdit = QLineEdit(self.format["thousandsseparator"]) self.thousandsLabel.setBuddy(self.thousandsEdit) self.thousandsEdit.setMaxLength(1) self.thousandsEdit.setValidator(QRegExpValidator(punctuationRe, self)) self.decimalMarkerLabel = QLabel("Decimal &marker") self.decimalMarkerEdit = QLineEdit(self.format["decimalmarker"]) self.decimalMarkerLabel.setBuddy(self.decimalMarkerEdit) self.decimalMarkerEdit.setMaxLength(1) self.decimalMarkerEdit.setValidator( QRegExpValidator(punctuationRe, self)) self.decimalMarkerEdit.setInputMask("X") self.decimalPlacesLabel = QLabel("&Decimal places") self.decimalPlacesSpinBox = QSpinBox() self.decimalPlacesLabel.setBuddy(self.decimalPlacesSpinBox) self.decimalPlacesSpinBox.setRange(0, 6) self.decimalPlacesSpinBox.setValue(self.format["decimalplaces"]) self.redNegativesCheckBox = QCheckBox("&Red negative numbers") self.redNegativesCheckBox.setChecked(self.format["rednegatives"]) self.buttonBox = QDialogButtonBox(QDialogButtonBox.Apply | QDialogButtonBox.Close) def layout_widgets(self): grid = QGridLayout() grid.addWidget(self.thousandsLabel, 0, 0) grid.addWidget(self.thousandsEdit, 0, 1) grid.addWidget(self.decimalMarkerLabel, 1, 0) grid.addWidget(self.decimalMarkerEdit, 1, 1) grid.addWidget(self.decimalPlacesLabel, 2, 0) grid.addWidget(self.decimalPlacesSpinBox, 2, 1) grid.addWidget(self.redNegativesCheckBox, 3, 0, 1, 2) grid.addWidget(self.buttonBox, 4, 0, 1, 2) self.setLayout(grid) def create_connections(self): self.buttonBox.button(QDialogButtonBox.Apply).clicked.connect( self.apply) self.buttonBox.rejected.connect(self.reject) def apply(self): thousands = unicode(self.thousandsEdit.text()) decimal = unicode(self.decimalMarkerEdit.text()) if thousands == decimal: QMessageBox.warning( self, "Format Error", "The thousands separator and the decimal marker " "must be different.") self.thousandsEdit.selectAll() self.thousandsEdit.setFocus() return if len(decimal) == 0: QMessageBox.warning(self, "Format Error", "The decimal marker may not be empty.") self.decimalMarkerEdit.selectAll() self.decimalMarkerEdit.setFocus() return self.format["thousandsseparator"] = thousands self.format["decimalmarker"] = decimal self.format["decimalplaces"] = (self.decimalPlacesSpinBox.value()) self.format["rednegatives"] = (self.redNegativesCheckBox.isChecked()) self.changed.emit()
class FilterDialog(QDialog): """ A dialog for editing filters """ solo_signatures = [ 'def filter(block):', 'def filter(segment):', 'def filter(rcg):', 'def filter(rc):', 'def filter(unit):' ] combi_signatures = [ 'def filter(blocks):', 'def filter(segments):', 'def filter(rcgs):', 'def filter(rcs):', 'def filter(units):' ] def __init__(self, groups, type=None, group=None, name=None, code=None, combined=False, on_exception=False, parent=None): QDialog.__init__(self, parent) self.setupUi() self.groups = groups if type: index = self.filterTypeComboBox.findText(type) if index >= 0: self.filterTypeComboBox.setCurrentIndex(index) self.populate_groups() if group: index = self.filterGroupComboBox.findText(group) if index >= 0: self.filterGroupComboBox.setCurrentIndex(index) if name: self.nameLineEdit.setText(name) if code: self.editor.set_text('\n'.join(code)) if name and code and type: self.filterTypeComboBox.setEnabled(False) self.combinedCheckBox.setChecked(combined) self.onExceptionCheckBox.setChecked(on_exception) def populate_groups(self): self.filterGroupComboBox.clear() self.filterGroupComboBox.addItem('') for g in sorted(self.groups[self.filterTypeComboBox.currentText()]): self.filterGroupComboBox.addItem(g) def setupUi(self): self.setWindowTitle('Edit filter') #self.resize(400, 300) self.signatureLabel = QLabel(self) self.signatureLabel.setText('def filter(block):') font = QFont('Some font that does not exist') font.setStyleHint(font.TypeWriter, font.PreferDefault) self.editor = CodeEditor(self) self.editor.setup_editor(linenumbers=False, language='py', scrollflagarea=False, codecompletion_enter=True, font=font, highlight_current_line=False, occurence_highlighting=False) self.editor.setCursor(Qt.IBeamCursor) self.editor.horizontalScrollBar().setCursor(Qt.ArrowCursor) self.editor.verticalScrollBar().setCursor(Qt.ArrowCursor) self.editor.set_text('return True') self.onExceptionCheckBox = QCheckBox(self) self.onExceptionCheckBox.setText('True on exception') self.onExceptionCheckBox.setToolTip('Determines if the filter will ' 'admit items if there is an ' 'exception during its execution') self.combinedCheckBox = QCheckBox(self) self.combinedCheckBox.setText('Combined filter') self.combinedCheckBox.setToolTip('Determines if the filter operates ' 'on single items (return True or ' 'False) or lists of items (return a ' 'list of items to be admitted)') self.filterTypeComboBox = QComboBox(self) self.filterTypeComboBox.addItem('Block') self.filterTypeComboBox.addItem('Segment') self.filterTypeComboBox.addItem('Recording Channel Group') self.filterTypeComboBox.addItem('Recording Channel') self.filterTypeComboBox.addItem('Unit') self.filterGroupComboBox = QComboBox(self) self.nameLineEdit = QLineEdit() self.dialogButtonBox = QDialogButtonBox(self) self.dialogButtonBox.setAutoFillBackground(False) self.dialogButtonBox.setOrientation(Qt.Horizontal) self.dialogButtonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.dialogButtonBox.setCenterButtons(True) gridLayout = QGridLayout(self) gridLayout.addWidget(self.signatureLabel, 0, 0, 1, 4) gridLayout.addWidget(self.editor, 1, 0, 1, 4) gridLayout.addWidget(self.onExceptionCheckBox, 2, 2, 1, 1) gridLayout.addWidget(self.combinedCheckBox, 2, 3, 1, 1) gridLayout.addWidget(QLabel('Type:', self), 2, 0) gridLayout.addWidget(self.filterTypeComboBox, 2, 1) gridLayout.addWidget(QLabel('Group:', self), 3, 0) gridLayout.addWidget(self.filterGroupComboBox, 3, 1, 1, 3) gridLayout.addWidget(QLabel('Name:', self), 4, 0) gridLayout.addWidget(self.nameLineEdit, 4, 1, 1, 3) gridLayout.addWidget(self.dialogButtonBox, 5, 0, 1, 4) self.connect(self.dialogButtonBox, SIGNAL('accepted()'), self.accept) self.connect(self.dialogButtonBox, SIGNAL('rejected()'), self.reject) self.combinedCheckBox.stateChanged.connect(self.combined_state_changed) self.connect(self.filterTypeComboBox, SIGNAL('currentIndexChanged(int)'), self.on_filterTypeComboBox_currentIndexChanged) def name(self): return self.nameLineEdit.text() def code(self): return [ self.editor.get_text_line(l) for l in xrange(self.editor.get_line_count()) ] def type(self): return self.filterTypeComboBox.currentText() def combined(self): return self.combinedCheckBox.isChecked() def group(self): if self.filterGroupComboBox.currentText() == '': return None return self.filterGroupComboBox.currentText() def on_exception(self): return self.onExceptionCheckBox.isChecked() def combined_state_changed(self): self.set_signature() def code_errors(self): code = self.signatureLabel.text() + '\n\t' code += '\n\t'.join(self.code()) try: compile(code, '<filter>', 'exec') except SyntaxError as e: return e.msg + ' (Line %d)' % (e.lineno - 1) return None def set_signature(self): if self.combinedCheckBox.isChecked(): self.signatureLabel.setText( self.combi_signatures[self.filterTypeComboBox.currentIndex()]) else: self.signatureLabel.setText( self.solo_signatures[self.filterTypeComboBox.currentIndex()]) def on_filterTypeComboBox_currentIndexChanged(self, index): self.set_signature() self.populate_groups() #noinspection PyCallByClass,PyTypeChecker,PyArgumentList def accept(self): if len(self.nameLineEdit.text()) < 1: QMessageBox.critical(self, 'Error saving filter', 'Please provide a name for the filter.') return if '"' in self.nameLineEdit.text(): QMessageBox.critical(self, 'Error saving filter', 'You cannot use " in the name of a filter.') return err = self.code_errors() if err: QMessageBox.critical(self, 'Error saving filter', 'Compile error:\n' + err) return QDialog.accept(self)
class OptionsDialog(QtHelper.EnhancedQDialog, Logger.ClassLogger): """ Update locations dialog """ def __init__(self, parent=None): """ Dialog to rename file or folder @param currentName: @type currentName: @param folder: @type folder: @param parent: @type parent: """ super(OptionsDialog, self).__init__(parent) self.createDialog() self.createConnections() def createDialog(self): """ Create qt dialog """ self.TIMEOUT_ANDROID_ACTION = Settings.instance().readValue( key='TestGenerator/timeout-android-action') self.timeoutAndroidLine = QLineEdit() self.timeoutAndroidLine.setText(str(self.TIMEOUT_ANDROID_ACTION)) validatorAndroid = QDoubleValidator(self) validatorAndroid.setNotation(QDoubleValidator.StandardNotation) self.timeoutAndroidLine.setValidator(validatorAndroid) self.timeoutAndroidLine.installEventFilter(self) self.agentNameLineAndroid = QLineEdit("AGENT_ANDROID") self.agentsAndroidList = QComboBox() self.agentsAndroidList.setMinimumWidth(300) optionAndroidLayout = QGridLayout() optionAndroidLayout.addWidget( QLabel(self.tr("Max time to run action:")), 1, 0) optionAndroidLayout.addWidget(self.timeoutAndroidLine, 1, 1) optionAndroidLayout.addWidget(QLabel(self.tr("Agent Key Name:")), 3, 0) optionAndroidLayout.addWidget(self.agentNameLineAndroid, 3, 1) optionAndroidLayout.addWidget(QLabel(self.tr("Agent:")), 4, 0) optionAndroidLayout.addWidget(self.agentsAndroidList, 4, 1) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setStyleSheet("""QDialogButtonBox { dialogbuttonbox-buttons-have-icons: 1; dialog-ok-icon: url(:/ok.png); dialog-cancel-icon: url(:/ko.png); }""") self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) mainLayout = QVBoxLayout() mainLayout.addLayout(optionAndroidLayout) mainLayout.addWidget(self.buttonBox) self.setLayout(mainLayout) self.setWindowTitle(self.tr("Android Options")) def createConnections(self): """ Create qt connections """ self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject)
def __createLayout(self): " Creates the dialog layout " self.resize(640, 480) self.setSizeGripEnabled(True) vboxLayout = QVBoxLayout(self) # Revisions to compare compareGroupbox = QGroupBox(self) compareGroupbox.setTitle("Revisions to compare") sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( compareGroupbox.sizePolicy().hasHeightForWidth()) compareGroupbox.setSizePolicy(sizePolicy) revisionLayout = QHBoxLayout(compareGroupbox) self.__lhsRevisionLabel = QLabel() self.__lhsRevisionLabel.setFrameStyle(QFrame.StyledPanel) self.__lhsResetButton = QToolButton() self.__lhsResetButton.setIcon(PixmapCache().getIcon(pluginHomeDir + 'svnclearrev.png')) self.__lhsResetButton.setFocusPolicy(Qt.NoFocus) self.__lhsResetButton.setEnabled(False) self.__lhsResetButton.setToolTip("Reset revision to compare") self.__lhsResetButton.clicked.connect(self.__onLHSReset) self.__rhsRevisionLabel = QLabel() self.__rhsRevisionLabel.setFrameStyle(QFrame.StyledPanel) self.__rhsResetButton = QToolButton() self.__rhsResetButton.setIcon(PixmapCache().getIcon(pluginHomeDir + 'svnclearrev.png')) self.__rhsResetButton.setFocusPolicy(Qt.NoFocus) self.__rhsResetButton.setEnabled(False) self.__rhsResetButton.setToolTip("Reset revision to compare") self.__rhsResetButton.clicked.connect(self.__onRHSReset) lhsLayout = QHBoxLayout() lhsLayout.addWidget(self.__lhsRevisionLabel) lhsLayout.addWidget(self.__lhsResetButton) rhsLayout = QHBoxLayout() rhsLayout.addWidget(self.__rhsRevisionLabel) rhsLayout.addWidget(self.__rhsResetButton) bothLayout = QVBoxLayout() bothLayout.addLayout(lhsLayout) bothLayout.addLayout(rhsLayout) revisionLayout.addLayout(bothLayout) self.__diffButton = QToolButton() self.__diffButton.setText("Diff") self.__diffButton.setFocusPolicy(Qt.NoFocus) self.__diffButton.setEnabled(False) self.__diffButton.clicked.connect(self.__onDiff) revisionLayout.addWidget(self.__diffButton) vboxLayout.addWidget(compareGroupbox) # Log table logHeaderFrame = QFrame() logHeaderFrame.setFrameStyle(QFrame.StyledPanel) logHeaderFrame.setAutoFillBackground(True) self.__setLightPalette(logHeaderFrame) logHeaderFrame.setFixedHeight(24) logHeaderLayout = QHBoxLayout() logHeaderLayout.setContentsMargins(3, 0, 0, 0) logHeaderLayout.addWidget(QLabel("Subversion log of " + self.__path)) logHeaderFrame.setLayout(logHeaderLayout) vboxLayout.addWidget(logHeaderFrame) self.__logView = QTreeWidget() self.__logView.setAlternatingRowColors(True) self.__logView.setRootIsDecorated(False) self.__logView.setItemsExpandable(False) self.__logView.setSortingEnabled(True) self.__logView.setItemDelegate(NoOutlineHeightDelegate(4)) self.__logViewHeader = QTreeWidgetItem( ["", "", "Revision", "Date", "Author", "Message"]) self.__logView.setHeaderItem(self.__logViewHeader) self.__logView.header().setSortIndicator(REVISION_COL, Qt.AscendingOrder) self.__logView.itemChanged.connect(self.__onLogViewChanged) vboxLayout.addWidget(self.__logView) # Diff part diffHeaderFrame = QFrame() diffHeaderFrame.setFrameStyle(QFrame.StyledPanel) diffHeaderFrame.setAutoFillBackground(True) self.__setLightPalette(diffHeaderFrame) diffHeaderFrame.setFixedHeight(24) diffLabel = QLabel("Diff") diffExpandingSpacer = QSpacerItem(10, 10, QSizePolicy.Expanding) self.__showHideDiffButton = QToolButton() self.__showHideDiffButton.setAutoRaise(True) self.__showHideDiffButton.setIcon(PixmapCache().getIcon('less.png')) self.__showHideDiffButton.setFixedSize(20, 20) self.__showHideDiffButton.setToolTip("Show diff") self.__showHideDiffButton.setFocusPolicy(Qt.NoFocus) self.__showHideDiffButton.clicked.connect(self.__onShowHideDiff) diffLayout = QHBoxLayout() diffLayout.setContentsMargins(3, 0, 0, 0) diffLayout.addWidget(diffLabel) diffLayout.addSpacerItem(diffExpandingSpacer) diffLayout.addWidget(self.__showHideDiffButton) diffHeaderFrame.setLayout(diffLayout) self.__diffViewer = DiffTabWidget() self.__diffViewer.setHTML(self.NODIFF) self.__diffViewer.setVisible(False) vboxLayout.addWidget(diffHeaderFrame) vboxLayout.addWidget(self.__diffViewer) # Buttons at the bottom buttonBox = QDialogButtonBox(self) buttonBox.setOrientation(Qt.Horizontal) buttonBox.setStandardButtons(QDialogButtonBox.Ok) buttonBox.button(QDialogButtonBox.Ok).setDefault(True) buttonBox.accepted.connect(self.close) vboxLayout.addWidget(buttonBox) return
class DlgChartingTemplate(QDialog): def __init__(self, parent=None): QDialog.__init__(self, parent) self.resize(100, 70) self.setWindowTitle("Template Properties") 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.groupBox1 = GroupBox(self) self.groupBox1.Caption = "" verticalLayoutDlg.addWidget(self.groupBox1) self.pnlSpace = ComboBoxPanel(self.groupBox1) self.pnlSpace.Caption = "Target Space" self.pnlSpace.LabelWidth = 120 self.groupBox1.Add = self.pnlSpace self.pnlDwg = TextBoxPanel(self.groupBox1) self.pnlDwg.Caption = "Drawing File" self.pnlDwg.LabelWidth = 120 self.groupBox1.Add = self.pnlDwg self.pnlTitle = TextBoxPanel(self.groupBox1) self.pnlTitle.Caption = "Titlee" self.pnlTitle.LabelWidth = 120 self.groupBox1.Add = self.pnlTitle 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) self.pnlSpace.Add(DrawingSpace.ModelSpace) self.pnlSpace.Add(DrawingSpace.PaperSpace) self.pnlSpace.SelectedIndex = 1 # if (String.IsNullOrEmpty(self.pnlDwg.Value)): # # DlgChartingTemplate height = self # # height.Height = height.Height - self.pnlDwg.Height # self.pnlDwg.Visible = False # self.pnlCodeType.Items = CodeTypeDesigPtAixm.Items def acceptDlg(self): self.accept() def get_TemplateDrawing(self): return self.pnlDwg.Value def set_TemplateDrawing(self, val): self.pnlDwg.Value = val TemplateDrawing = property(get_TemplateDrawing, set_TemplateDrawing, None, None) def get_TemplateSpace(self): if (self.pnlSpace.SelectedIndex == 0): return DrawingSpace.ModelSpace return DrawingSpace.PaperSpace def set_TemplateSpace(self, val): if (val == DrawingSpace.ModelSpace): self.pnlSpace.SelectedIndex = 0 return self.pnlSpace.SelectedIndex = 1 TemplateSpace = property(get_TemplateSpace, set_TemplateSpace, None, None) def get_TemplateTitle(self): return self.pnlTitle.Value def set_TemplateTitle(self, val): self.pnlTitle.Value = val TemplateTitle = property(get_TemplateTitle, set_TemplateTitle, None, None) @staticmethod def smethod_0(parent, string_0, drawingSpace_0, string_1): flag = False dlgChartingTemplate = DlgChartingTemplate(parent) dlgChartingTemplate.TemplateTitle = string_0 dlgChartingTemplate.TemplateDrawing = string_1 dlgChartingTemplate.TemplateSpace = drawingSpace_0 result = dlgChartingTemplate.exec_() if (not result): flag = False else: string_0 = dlgChartingTemplate.TemplateTitle drawingSpace_0 = dlgChartingTemplate.TemplateSpace flag = True return flag, string_0, drawingSpace_0 @staticmethod def smethod_1(parent, string_0, drawingSpace_0): flag = False dlgChartingTemplate = DlgChartingTemplate(parent) dlgChartingTemplate.TemplateTitle = string_0 dlgChartingTemplate.TemplateSpace = drawingSpace_0 result = dlgChartingTemplate.exec_() if (not result): flag = False else: string_0 = dlgChartingTemplate.TemplateTitle drawingSpace_0 = dlgChartingTemplate.TemplateSpace flag = True return flag, string_0, drawingSpace_0
class OperatorValueDialog(QtHelper.EnhancedQDialog): """ Operator dialog """ def __init__(self, parent, currentOperator={}, liteMode=False): """ Operator to fill parameter description @param dataArgs: @type dataArgs: @param parent: @type parent: """ super(OperatorValueDialog, self).__init__(parent) self.parentWidget = parent self.liteMode = liteMode self.currentOperator = currentOperator self.createDialog() self.createConnections() def createDialog(self): """ Create qt dialog """ self.buttonBox = QDialogButtonBox(self) self.buttonBox.setStyleSheet("""QDialogButtonBox { dialogbuttonbox-buttons-have-icons: 1; dialog-ok-icon: url(:/ok.png); dialog-cancel-icon: url(:/test-close-black.png); }""") self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) mainLayout = QHBoxLayout() main2Layout = QHBoxLayout() titleLabel = QLabel(self.currentOperator['operator']) font = QFont() font.setBold(True) titleLabel.setFont(font) self.opType = QComboBox() if not self.liteMode: for i in xrange(len(LIST_CONDITIONS)): self.opType.addItem(LIST_CONDITIONS[i].title()) if self.currentOperator['operator'] == LIST_CONDITIONS[ i].title(): self.opType.setCurrentIndex(i) else: for i in xrange(len(LIST_CONDITIONS_LITE)): self.opType.addItem(LIST_CONDITIONS_LITE[i].title()) if self.currentOperator['operator'] == LIST_CONDITIONS_LITE[ i].title(): self.opType.setCurrentIndex(i) main2Layout.addWidget(titleLabel) main2Layout.addWidget(self.opType) if not self.liteMode: self.textValue = QTextEdit() self.textValue.setFixedHeight(HEIGHT_TEXT_AREA) self.textValue.setMinimumWidth(WIDTH_TEXT_AREA) radioGroup = QButtonGroup(self) self.strRadioButton = QRadioButton("string") self.strRadioButton.setChecked(True) self.inRadioButton = QRadioButton("inputs") self.outRadioButton = QRadioButton("outputs") self.varRadioButton = QRadioButton("variables") radioGroup.addButton(self.strRadioButton) radioGroup.addButton(self.inRadioButton) radioGroup.addButton(self.outRadioButton) radioGroup.addButton(self.varRadioButton) self.inputsCombo = QComboBox() for inpt in self.parentWidget.getInputs(): self.inputsCombo.addItem(inpt['name']) self.outputsCombo = QComboBox() for inpt in self.parentWidget.getOutputs(): self.outputsCombo.addItem(inpt['name']) self.variablesCombo = QComboBox() self.variablesCombo.addItems(self.parentWidget.variables) if self.currentOperator['type'] == 'string': self.strRadioButton.setChecked(True) self.textValue.setText(self.currentOperator['value']) if self.currentOperator['type'] == 'inputs': self.inRadioButton.setChecked(True) for x in xrange(self.inputsCombo.count()): if self.inputsCombo.itemText( x) == self.currentOperator['value']: self.inputsCombo.setCurrentIndex(x) if self.currentOperator['type'] == 'outputs': self.outRadioButton.setChecked(True) for x in xrange(self.outputsCombo.count()): if self.outputsCombo.itemText( x) == self.currentOperator['value']: self.outputsCombo.setCurrentIndex(x) if self.currentOperator['type'] == 'variables': self.varRadioButton.setChecked(True) for x in xrange(self.variablesCombo.count()): if self.variablesCombo.itemText( x) == self.currentOperator['value']: self.variablesCombo.setCurrentIndex(x) mainLayout.addWidget(self.strRadioButton) mainLayout.addWidget(self.textValue) mainLayout.addWidget(self.inRadioButton) mainLayout.addWidget(self.inputsCombo) mainLayout.addWidget(self.outRadioButton) mainLayout.addWidget(self.outputsCombo) mainLayout.addWidget(self.varRadioButton) mainLayout.addWidget(self.variablesCombo) finalLayout = QVBoxLayout() finalLayout.addLayout(main2Layout) finalLayout.addLayout(mainLayout) finalLayout.addWidget(self.buttonBox) self.setLayout(finalLayout) self.setWindowTitle(self.tr("Operators configuration")) self.setMinimumWidth(500) self.center() def createConnections(self): """ Create qt connections """ self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) def getValue(self): """ Return value """ self.currentOperator['operator'] = unicode(self.opType.currentText()) if not self.liteMode: if self.currentOperator['operator'].lower() == OP_ANY: self.currentOperator['type'] = 'string' self.currentOperator['value'] = '' else: if self.strRadioButton.isChecked(): self.currentOperator['type'] = 'string' self.currentOperator['value'] = unicode( self.textValue.toPlainText()) if self.inRadioButton.isChecked(): self.currentOperator['type'] = 'inputs' self.currentOperator['value'] = unicode( self.inputsCombo.currentText()) if self.outRadioButton.isChecked(): self.currentOperator['type'] = 'outputs' self.currentOperator['value'] = unicode( self.outputsCombo.currentText()) if self.varRadioButton.isChecked(): self.currentOperator['type'] = 'variables' self.currentOperator['value'] = unicode( self.variablesCombo.currentText()) return self.currentOperator
class DlgCrcReadWrite(QDialog): def __init__(self, parent, rwFlag="r"): QDialog.__init__(self, parent) self.rwFlag = rwFlag self.resize(100, 70) if self.rwFlag == "r": self.setWindowTitle("CRC Reader") else: self.setWindowTitle("CRC Writer") 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.groupBox1 = GroupBox(self) self.groupBox1.Caption = "" verticalLayoutDlg.addWidget(self.groupBox1) self.pnlFile = TextBoxPanel(self.groupBox1) self.pnlFile.Caption = "File" self.pnlFile.LabelWidth = 120 self.pnlFile.textBox.setMaximumWidth(200) self.pnlFile.textBox.setMinimumWidth(200) self.pnlFile.Button = "openData.png" self.groupBox1.Add = self.pnlFile self.pnlSuppliedCrcValue = TextBoxPanel(self.groupBox1) self.pnlSuppliedCrcValue.Caption = "Supplied CRC Value" self.pnlSuppliedCrcValue.LabelWidth = 120 self.pnlSuppliedCrcValue.Enabled = False self.groupBox1.Add = self.pnlSuppliedCrcValue if self.rwFlag == "w": self.pnlSuppliedCrcValue.Visible = False self.pnlCalculatedCrcValue = TextBoxPanel(self.groupBox1) self.pnlCalculatedCrcValue.Caption = "Calculated CRC Value" self.pnlCalculatedCrcValue.LabelWidth = 120 self.pnlCalculatedCrcValue.Enabled = False self.groupBox1.Add = self.pnlCalculatedCrcValue self.btnBoxOkCancel = QDialogButtonBox(self) self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel")) self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) btnQuit = self.btnBoxOkCancel.button(QDialogButtonBox.Ok) btnQuit.setText("Quit") btnCancel = self.btnBoxOkCancel.button(QDialogButtonBox.Cancel) btnCancel.setVisible(False) self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg) self.connect(self.pnlFile, SIGNAL("Event_1"), self.pnlFileEvent_1) verticalLayoutDlg.addWidget(self.btnBoxOkCancel) def pnlFileEvent_1(self): inputFilePath = QFileDialog.getOpenFileName( self, "Open Xml File", QCoreApplication.applicationDirPath(), "Xml Files (*.xml)") if inputFilePath == "": return fileInfo = QFileInfo(inputFilePath) self.pnlFile.Value = fileInfo.fileName() contents = None with open(inputFilePath, 'rb', 0) as tempFile: contents = tempFile.read() tempFile.close() bytes = FasDataBlockFile.CRC_Calculation(contents) string_0 = QString(inputFilePath) crcFileDir = string_0.left(string_0.length() - 3) + "crc" fileInfo = QFileInfo(crcFileDir) if self.rwFlag == "r": if not fileInfo.exists(): QMessageBox.warning(self, "Warning", "CRC file is not existing.") return crcFileContents = None with open(crcFileDir, 'rb', 0) as tempFileCrc: crcFileContents = tempFileCrc.read() tempFileCrc.close() if bytes != crcFileContents: self.pnlCalculatedCrcValue.textBox.setStyleSheet( "color: rgb(255, 0, 0);") else: self.pnlCalculatedCrcValue.textBox.setStyleSheet( "color: rgb(0, 0, 0);") self.pnlSuppliedCrcValue.Value = crcFileContents self.pnlCalculatedCrcValue.Value = bytes else: fileStream = open(crcFileDir, 'wb') fileStream.write(bytes) fileStream.close() self.pnlCalculatedCrcValue.Value = bytes def acceptDlg(self): self.accept() @staticmethod def smethod_0(parent, inputFilePath, rwFlag="r"): flag = False dlgCrcReadWrite = DlgCrcReadWrite(parent, rwFlag) resultDlg = dlgCrcReadWrite.exec_() if (resultDlg == 0): flag = False else: flag = True return flag
class DlgAixmHolding(QDialog): def __init__(self, parent = None): QDialog.__init__(self, parent) self.resize(290, 136); self.setWindowTitle("Instrument Approach Procedure (IAP)") 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.pnlBasedOn = ComboBoxPanel(self.groupBox) self.pnlBasedOn.Caption = "Based On" self.pnlBasedOn.Button = "coordinate_capture.png" self.groupBox.Add = self.pnlBasedOn self.pnlType = ComboBoxPanel(self.groupBox) self.pnlType.Caption = "Type" self.groupBox.Add = self.pnlType self.txtDescription = TextBoxPanel(self.groupBox, True) self.txtDescription.Caption = "Description" self.groupBox.Add = self.txtDescription self.txtRemarks = TextBoxPanel(self.groupBox, True) self.txtRemarks.Caption = "Remarks" self.groupBox.Add = self.txtRemarks self.btnBoxOkCancel = QDialogButtonBox(self) self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel")); self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok); self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg) self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject) self.connect(self.pnlBasedOn, SIGNAL("Event_3"), self.pnlBasedOn_Event_3) verticalLayoutDlg.addWidget(self.btnBoxOkCancel) self.data = None self.table = None self.selected = None; self.CaptureCoordTool = CaptureCoordinateToolUpdate(define._canvas) self.connect(self.CaptureCoordTool, SIGNAL("resultPointValueList"), self.resultPointValueListMethod) def pnlBasedOn_Event_3(self): CaptureCoordTool = CaptureCoordinateToolUpdate(define._canvas) self.connect(CaptureCoordTool, SIGNAL("resultPointValueList"), self.resultPointValueListMethod) define._canvas.setMapTool(self.CaptureCoordTool) def resultPointValueListMethod(self, resultValueList): if len(resultValueList) > 0: point3d = Point3D(float(resultValueList[1]), float(resultValueList[2]), float(resultValueList[3])) resultDlg, procEntityBase = DlgAixmSelectPosition.smethod_0(self, self.data, point3d, ProcEntityListType.Holding) if (resultDlg and procEntityBase != None): if (not self.pnlBasedOn.Contains(procEntityBase)): self.pnlBasedOn.Add(procEntityBase); self.pnlBasedOn.SelectedIndex = self.pnlBasedOn.IndexOf(procEntityBase); def acceptDlg(self): selectedItem = self.pnlBasedOn.SelectedItem; codeTypeHoldProcAixm = self.pnlType.SelectedItem for row in self.table: flag = True; if (self.selected != None and row == self.selected): flag = False; if (row["basedOnEnt"] != selectedItem): flag = False; if (row["codeType"] != codeTypeHoldProcAixm): flag = False; if (not flag): continue; strS = "Cannot create a duplicate procedure entry.\n\nBased on = {0}\nType = {1}".format(self.pnlBasedOn.SelectedItem, self.pnlType.SelectedItem); QMessageBox.warning(self, "Error", strS); return; self.accept() def method_6(self): pass @staticmethod def smethod_0(dataBaseHoldings_0, dataBaseProcedureData_0, dataRow_0): flag = False; dlgAixmHolding = DlgAixmHolding() dlgAixmHolding.data = dataBaseProcedureData_0; dlgAixmHolding.table = dataBaseHoldings_0; dlgAixmHolding.selected = dataRow_0; dataBaseProcedureData_0.method_59(dlgAixmHolding.pnlBasedOn, ProcEntityListType.Holding); dlgAixmHolding.pnlType.Items = CodeTypeHoldProcAixm.Items; if (dataRow_0 != None and len(dataRow_0) > 0): dlgAixmHolding.pnlBasedOn.SelectedIndex = dlgAixmHolding.pnlBasedOn.IndexOf(dataRow_0["basedOnEnt"]); dlgAixmHolding.pnlType.SelectedIndex = dlgAixmHolding.pnlType.method_3(dataRow_0["codeType"]); if (dataRow_0["txtDescr"] != None): dlgAixmHolding.txtDescription.Value = dataRow_0["txtDescr"]; if (dataRow_0["txtRmk"] != None): dlgAixmHolding.txtRemarks.Value = dataRow_0["txtRmk"]; resultDlg = dlgAixmHolding.exec_() if (resultDlg == 1): dataRow0 = dataRow_0 == None or len(dataRow_0) == 0; strS = []; if (not dataRow0): for a in dataBaseHoldings_0.nameList: strS.append(None) # str = new string[dataBaseHoldings_0.Columns.Count]; i = 0 for name in dataBaseHoldings_0.nameList: strS[i] = dataRow_0[name] i += 1 else: dataRow_0 = dataBaseHoldings_0.NewRow(); dataRow_0["basedOnEnt"] = dlgAixmHolding.pnlBasedOn.SelectedItem; if (dataRow0): dataRow_0["oldBasedOnEnt"] = dataRow_0["basedOnEnt"]; dataRow_0["codeType"] = dlgAixmHolding.pnlType.SelectedItem; if (dataRow0): dataRow_0["oldCodeType"] = dataRow_0["codeType"]; if (not String.IsNullOrEmpty(dlgAixmHolding.txtDescription.Value)): dataRow_0["txtDescr"] = dlgAixmHolding.txtDescription.Value; else: dataRow_0["txtDescr"] = None; if (not String.IsNullOrEmpty(dlgAixmHolding.txtRemarks.Value)): dataRow_0["txtRmk"] = dlgAixmHolding.txtRemarks.Value; else: dataRow_0["txtRmk"] = None; if (dataRow0): dataRow_0["procLegs"] = DataBaseProcedureLegs(); dataRow_0["procLegsEx"] = DataBaseProcedureLegsEx(); if (not dataRow0): num = 1; while (num < len(strS)): if (not strS[num] == dataRow_0[dataRow_0.nameList[num]]): dataRow_0["changed"] = "True"; if (dataRow0): dataBaseHoldings_0.RowsAdd(dataRow_0); flag = True; return flag; else: num += 1; else: dataRow_0["new"] = "True"; if (dataRow0): dataBaseHoldings_0.RowsAdd(dataRow_0); flag = True; return flag; return flag
def registerEvent(self): selection = self.ui.modulesList.selectedItems() if not selection: return try: module = self.weboob.modules_loader.get_or_load_module(unicode(selection[0].text()).lower()) except ModuleLoadError: module = None if not module: return dialog = QDialog(self) vbox = QVBoxLayout(dialog) if module.website: website = 'on the website <b>%s</b>' % module.website else: website = 'with the module <b>%s</b>' % module.name vbox.addWidget(QLabel('To create an account %s, please provide this information:' % website)) formlayout = QFormLayout() props_widgets = OrderedDict() for key, prop in module.klass.ACCOUNT_REGISTER_PROPERTIES.iteritems(): widget = QtValue(prop) formlayout.addRow(QLabel(u'%s:' % prop.label), widget) props_widgets[prop.id] = widget vbox.addLayout(formlayout) buttonBox = QDialogButtonBox(dialog) buttonBox.setStandardButtons(QDialogButtonBox.Ok|QDialogButtonBox.Cancel) buttonBox.accepted.connect(dialog.accept) buttonBox.rejected.connect(dialog.reject) vbox.addWidget(buttonBox) end = False while not end: end = True if dialog.exec_(): account = Account() account.properties = {} for key, widget in props_widgets.iteritems(): try: v = widget.get_value() except ValueError as e: QMessageBox.critical(self, self.tr('Invalid value'), unicode(self.tr('Invalid value for field "%s":<br /><br />%s')) % (key, e)) end = False break else: account.properties[key] = v if end: try: module.klass.register_account(account) except AccountRegisterError as e: QMessageBox.critical(self, self.tr('Error during register'), unicode(self.tr('Unable to register account %s:<br /><br />%s')) % (website, e)) end = False else: for key, value in account.properties.iteritems(): if key in self.config_widgets: self.config_widgets[key][1].set_value(value)