def __init__(self, strip, parent=None): super(LEDDialog,self).__init__(parent) self.strip = strip self.buttons = [] layout = QVBoxLayout() btnlayout = QGridLayout() self.btnmapper = QSignalMapper() for i in xrange(int(self.strip.config['nleds'])): p = QPushButton() p.setFixedWidth(40) p.setFlat(True) p.setAutoFillBackground(True) self.btnmapper.setMapping( p, i) p.clicked.connect( self.btnmapper.map) self.buttons += [[p,QColor()]] btnlayout.addWidget(p, i/self.rowwidth, i%self.rowwidth) self.btnmapper.mapped['int'].connect(self.chooseColor) layout.addLayout(btnlayout) ctrllayout = QHBoxLayout() p = QPushButton("Refresh") p.clicked.connect(self.refresh) ctrllayout.addWidget(p) p = QPushButton("Set") p.clicked.connect(self.set) ctrllayout.addWidget(p) p = QPushButton("Close") p.clicked.connect(self.close) ctrllayout.addWidget(p) layout.addLayout(ctrllayout) self.setLayout( layout) self.refresh()
def __init__(self, mainwindow): super(SessionManagerDialog, self).__init__(mainwindow) self.setWindowModality(Qt.WindowModal) layout = QVBoxLayout() self.setLayout(layout) self.sessions = SessionList(self) layout.addWidget(self.sessions) self.imp = QPushButton(self) self.exp = QPushButton(self) self.act = QPushButton(self) self.imp.clicked.connect(self.importSession) self.exp.clicked.connect(self.exportSession) self.act.clicked.connect(self.activateSession) self.sessions.layout().addWidget(self.imp, 5, 1) self.sessions.layout().addWidget(self.exp, 6, 1) self.sessions.layout().addWidget(self.act, 7, 1) layout.addWidget(widgets.Separator()) self.buttons = b = QDialogButtonBox(self) layout.addWidget(b) b.setStandardButtons(QDialogButtonBox.Close) b.rejected.connect(self.accept) userguide.addButton(b, "sessions") self.sessions.load() app.translateUI(self) self.sessions.changed.connect(self.enableButtons) self.sessions.listBox.itemSelectionChanged.connect(self.enableButtons) self.enableButtons()
def display_information_message_bar( title=None, message=None, more_details=None, button_text=tr('Show details ...'), duration=8): """ Display an information message bar. :param title: The title of the message bar. :type title: str :param message: The message inside the message bar. :type message: str :param more_details: The message inside the 'Show details' button. :type more_details: str :param button_text: The text of the button if 'more_details' is not empty. :type button_text: str :param duration: The duration for the display, default is 8 seconds. :type duration: int """ widget = iface.messageBar().createMessage(title, message) if more_details: button = QPushButton(widget) button.setText(button_text) button.pressed.connect( lambda: display_information_message_box( title=title, message=more_details)) widget.layout().addWidget(button) iface.messageBar().pushWidget(widget, QgsMessageBar.INFO, duration)
class LocalityWidGet(QWidget): """Modal para alterer a localidade da previção do tempo""" def __init__(self): super(LocalityWidGet, self).__init__() self.setWindowTitle = 'Settings' self.setGeometry(450, 300, 400, 200) self.locality_label = QLabel('Localidade: ',self) self.locality_label.move(20, 35) self.locality_label_example = QLabel('Exemplo: Porto Alegre, RS', self) self.locality_label_example.move(100, 60) self.locality_input_text = QLineEdit(self) self.locality_input_text.move(100, 30) wc = WeatherClient() current_locality = wc.get_place() self.locality_input_text.setText(current_locality.replace('+', ', ').decode('utf-8')) self.btnOk = QPushButton('OK', self) self.btnOk.move(250, 150) self.btnOk.clicked.connect(lambda: Eventer.save_new_locality(self)) self.show()
def __init__(self, project, content, itemRelated, parent=None): QWidget.__init__(self, parent) self.__content = content.toMap() self.__project = project self.__favorite = QPushButton(self) self.__delete = QPushButton(self) self.__delete.setIcon(QIcon(resources.IMAGES['delProj'])) self.__name = QLineEdit(self) self.__itemRelated = itemRelated self.setMouseTracking(True) self.__name.setText(self.__content[QString("name")].toString()) if QString("description") in self.__content: description = self.__content[QString("description")].toString() else: description = self.tr("no description available") self.__name.setToolTip(self.tr(self.__project) + '\n\n' + description) self.__delete.setToolTip(self.tr("Click to delete from the list")) self.__favorite.setToolTip(self.tr("Click to dock on the list")) hbox = QHBoxLayout() self.setLayout(hbox) hbox.setContentsMargins(0, 0, 0, 0) hbox.addWidget(self.__favorite) hbox.addWidget(self.__name) hbox.addWidget(self.__delete) self.__name.setCursor(QCursor(Qt.ArrowCursor)) self.__name.setReadOnly(True) self.connect(self.__favorite, SIGNAL("clicked(bool)"), self.__on_click_on_favorite) self.connect(self.__delete, SIGNAL("clicked(bool)"), self.__on_click_on_delete) #TODO: Change this click listen it doesn't work with ReadOnly = True self.connect(self.__name, SIGNAL("cursorPositionChanged(int, int)"), self.__on_click_on_name) self._set_favorite(self.__content[QString("isFavorite")].toBool())
def updateTableForSlot(self, slot): """ Update the table row that corresponds to the given slot of the top-level operator (could be either input slot) """ row = self.getSlotIndex( self.topLevelOperator.ExportPath, slot ) assert row != -1, "Unknown input slot!" if not self.topLevelOperator.ExportPath[row].ready() or\ not self.topLevelOperator.RawDatasetInfo[row].ready(): return try: nickname = self.topLevelOperator.RawDatasetInfo[row].value.nickname exportPath = self.topLevelOperator.ExportPath[row].value except Slot.SlotNotReadyError: # Sadly, it is possible to get here even though we checked for .ready() immediately beforehand. # That's because the graph has a diamond-shaped DAG of connections, but the graph has no transaction mechanism # (It's therefore possible for RawDatasetInfo[row] to be ready() even though it's upstream partner is NOT ready. return self.batchOutputTableWidget.setItem( row, Column.Dataset, QTableWidgetItem( decode_to_qstring(nickname, 'utf-8') ) ) self.batchOutputTableWidget.setItem( row, Column.ExportLocation, QTableWidgetItem( decode_to_qstring(exportPath) ) ) exportNowButton = QPushButton("Export") exportNowButton.setToolTip("Generate individual batch output dataset.") exportNowButton.clicked.connect( bind(self.exportResultsForSlot, self.topLevelOperator[row] ) ) self.batchOutputTableWidget.setCellWidget( row, Column.Action, exportNowButton ) # Select a row if there isn't one already selected. selectedRanges = self.batchOutputTableWidget.selectedRanges() if len(selectedRanges) == 0: self.batchOutputTableWidget.selectRow(0)
def show(self, webPages): settings = Settings() server = xmlrpclib.Server(settings.serverAddress) self.setWindowTitle('updates') layout = self.layout() if layout == None: layout = QVBoxLayout() label = QLabel('Some Web Pages have changed:') layout.addWidget(label) for webPage in webPages: label = QLabel('<a href=' + webPage + '>' + self._truncate(webPage) + '</a>' ) label.setOpenExternalLinks(True) layout.addWidget(label) #buttonBox = QDialogButtonBox(QDialogButtonBox.Ok) moreButton = QPushButton('More...') moreButton.setMaximumWidth(60) self.connect(moreButton, SIGNAL('clicked()'), self.showDiffWindow) layout.addWidget(moreButton) self.setLayout(layout) if debug.verbose: print('DEBUG: Showing notification dialog') QDialog.show(self) QTimer.singleShot(0, self.fixPosition) QTimer.singleShot(self._timeout, self.hide)
def __init__(self, layers): """ Constructor """ QDialog.__init__(self) self.__layers = layers self.setWindowTitle(QCoreApplication.translate("VDLTools", "Edition Confirmation")) self.__layout = QGridLayout() titleLabel = QLabel(QCoreApplication.translate("VDLTools", "Do you really want to edit these layers ?")) self.__layout.addWidget(titleLabel, 0, 0, 1, 2) pos = 1 for layer in self.__layers: label = QLabel(" - " + layer.name()) self.__layout.addWidget(label, pos, 0, 1, 2) pos += 1 self.__cancelButton = QPushButton(QCoreApplication.translate("VDLTools", "Cancel")) self.__cancelButton.setMinimumHeight(20) self.__cancelButton.setMinimumWidth(100) pos = len(self.__layers) + 1 self.__layout.addWidget(self.__cancelButton, pos, 0) self.__okButton = QPushButton(QCoreApplication.translate("VDLTools", "OK")) self.__okButton.setMinimumHeight(20) self.__okButton.setMinimumWidth(100) self.__layout.addWidget(self.__okButton, pos, 1) self.setLayout(self.__layout)
def __init__(self, model, parent=None): super().__init__(parent) self._view = QTableView() self._view.setModel(model) cancelButton = QPushButton(_("cancel")) cancelButton.clicked.connect(self.reject) okButton = QPushButton(_("OK")) okButton.setDefault(True) okButton.clicked.connect(self.accept) addButton = QPushButton("+") addButton.clicked.connect(self.add) buttonBox = QHBoxLayout() buttonBox.addWidget(addButton) buttonBox.addStretch(1) buttonBox.addWidget(cancelButton) buttonBox.addWidget(okButton) layout = QVBoxLayout() layout.addWidget(self._view) layout.addLayout(buttonBox) self.setLayout(layout) self.accepted.connect(self.save) self.setWindowTitle(_("Admin.edit" + model.table)) self.resize(600, 300) self._view.resizeColumnsToContents()
class EkdColorPropertie(EkdPropertie): """ Définition de la propriété correspondant à une Couleur """ def __init__(self, prop, name, value, section=None ): super(EkdColorPropertie, self).__init__(prop, name, value, EkdPropertie.COLOR, section) self.label = QLabel(name) self.widget = QFrame() self.layout = QHBoxLayout(self.widget) self.line = QLineEdit(value) self.value = value self.line.setReadOnly(True) self.layout.addWidget(self.line) self.color = QPixmap(15, 15) self.color.fill(QColor.fromRgb(int("%d" % int(self.value, 16)))) self.boutton = QPushButton(QIcon(self.color), u"") self.boutton.setFixedSize(25,25) self.layout.addWidget(self.boutton) # Quand on clique sur le boutton on défini la couleur self.connect(self.boutton, SIGNAL("clicked()"), self.updateColor) def updateColor(self): newcolor = QColorDialog.getColor(QColor.fromRgb(int("%d" % int(self.value, 16))), None )# Non supporté sous Jaunty ?? if newcolor.isValid(): self.value = str("%x" % newcolor.rgb())[2:] self.color.fill(QColor.fromRgb(int("%d" % int(self.value, 16)))) self.boutton.setIcon(QIcon(self.color)) self.line.setText(self.value) EkdConfig.set(self.section, self.id, self.value)
def __init__(self): """ Constructor """ QDialog.__init__(self) self.setWindowTitle(QCoreApplication.translate("VDLTools", "Display Attributes Confirmation")) self.resize(300, 100) self.__layout = QGridLayout() self.__confirmLabel = QLabel( QCoreApplication.translate("VDLTools", "Do you want to display the attributes tables for the selected features ?")) self.__layout.addWidget(self.__confirmLabel, 0, 0, 1, 2) self.__okButton = QPushButton(QCoreApplication.translate("VDLTools", "Yes")) self.__okButton.setMinimumHeight(20) self.__okButton.setMinimumWidth(100) self.__cancelButton = QPushButton(QCoreApplication.translate("VDLTools", "No")) self.__cancelButton.setMinimumHeight(20) self.__cancelButton.setMinimumWidth(100) self.__layout.addWidget(self.__okButton, 1, 0) self.__layout.addWidget(self.__cancelButton, 1, 1) self.setLayout(self.__layout)
def __init__(self): QWidget.__init__(self) self.setContextMenuPolicy(Qt.DefaultContextMenu) self.setMinimumHeight(38) hbox = QHBoxLayout(self) self.btnPrevious = QPushButton(QIcon(resources.IMAGES["nav-code-left"]), "") self.btnPrevious.setObjectName("navigation_button") self.btnPrevious.setToolTip(self.tr("Right click to change navigation options")) self.btnNext = QPushButton(QIcon(resources.IMAGES["nav-code-right"]), "") self.btnNext.setObjectName("navigation_button") self.btnNext.setToolTip(self.tr("Right click to change navigation options")) hbox.addWidget(self.btnPrevious) hbox.addWidget(self.btnNext) self.setContentsMargins(0, 0, 0, 0) self.menuNavigate = QMenu(self.tr("Navigate")) self.codeAction = self.menuNavigate.addAction(self.tr("Code Jumps")) self.codeAction.setCheckable(True) self.codeAction.setChecked(True) self.bookmarksAction = self.menuNavigate.addAction(self.tr("Bookmarks")) self.bookmarksAction.setCheckable(True) self.breakpointsAction = self.menuNavigate.addAction(self.tr("Breakpoints")) self.breakpointsAction.setCheckable(True) # 0 = Code Jumps # 1 = Bookmarks # 2 = Breakpoints self.operation = 0 self.connect(self.codeAction, SIGNAL("triggered()"), self._show_code_nav) self.connect(self.breakpointsAction, SIGNAL("triggered()"), self._show_breakpoints) self.connect(self.bookmarksAction, SIGNAL("triggered()"), self._show_bookmarks)
class EkdPathPropertie(EkdPropertie): """ Définition de la propriété correspondant à un chemin """ def __init__(self, prop, name, value, section=None ): super(EkdPathPropertie, self).__init__(prop, name, value, EkdPropertie.PATH, section) self.label = QLabel(name) self.widget = QFrame() self.layout = QHBoxLayout(self.widget) self.line = QLineEdit(value) self.line.setReadOnly(True) self.layout.addWidget(self.line) self.boutton = QPushButton(u"...") self.boutton.setFixedSize(25,25) self.layout.addWidget(self.boutton) # Quand on clique sur le boutton on défini le path self.connect(self.boutton, SIGNAL("clicked()"), self.updatePath) def updatePath(self): newpath = QFileDialog.getExistingDirectory(None, _(u"Choisissez un chemin"), self.value ) if newpath: self.value = newpath self.line.setText(self.value) EkdConfig.set(self.section, self.id, self.value)
def _setupUi(self): self.setWindowTitle(tr("Error Report")) self.resize(553, 349) self.verticalLayout = QVBoxLayout(self) self.label = QLabel(self) self.label.setText(tr("Something went wrong. How about reporting the error?")) self.label.setWordWrap(True) self.verticalLayout.addWidget(self.label) self.errorTextEdit = QPlainTextEdit(self) self.errorTextEdit.setReadOnly(True) self.verticalLayout.addWidget(self.errorTextEdit) msg = tr( "Error reports should be reported as Github issues. You can copy the error traceback " "above and paste it in a new issue (bonus point if you run a search to make sure the " "issue doesn't already exist). What usually really helps is if you add a description " "of how you got the error. Thanks!" "\n\n" "Although the application should continue to run after this error, it may be in an " "unstable state, so it is recommended that you restart the application." ) self.label2 = QLabel(msg) self.label2.setWordWrap(True) self.verticalLayout.addWidget(self.label2) self.horizontalLayout = QHBoxLayout() self.horizontalLayout.addItem(horizontalSpacer()) self.dontSendButton = QPushButton(self) self.dontSendButton.setText(tr("Close")) self.dontSendButton.setMinimumSize(QSize(110, 0)) self.horizontalLayout.addWidget(self.dontSendButton) self.sendButton = QPushButton(self) self.sendButton.setText(tr("Go to Github")) self.sendButton.setMinimumSize(QSize(110, 0)) self.sendButton.setDefault(True) self.horizontalLayout.addWidget(self.sendButton) self.verticalLayout.addLayout(self.horizontalLayout)
def keyPressEvent(self, event): if self.isChecked() and event.text() != "": self.setText(QKeySequence(event.key() | int(event.modifiers())).toString(QKeySequence.NativeText)) self.setChecked(False) self.editingFinished.emit() else: QPushButton.keyPressEvent(self, event)
class EditPane(QWidget): def __init__(self, model): QWidget.__init__(self) self._setupUi() self.model = model self.model.view = self self.normalButton.clicked.connect(partial(self.model.app.change_state_of_selected, ElementState.Normal)) self.titleButton.clicked.connect(partial(self.model.app.change_state_of_selected, ElementState.Title)) self.footnoteButton.clicked.connect(partial(self.model.app.change_state_of_selected, ElementState.Footnote)) self.ignoreButton.clicked.connect(partial(self.model.app.change_state_of_selected, ElementState.Ignored)) self.tofixButton.clicked.connect(partial(self.model.app.change_state_of_selected, ElementState.ToFix)) self.hideIgnoredCheckBox.stateChanged.connect(self.hideIgnoredCheckBoxStateChanged) self.textEdit.textChanged.connect(self.textEditTextChanged) self.saveEditsButton.clicked.connect(self.model.save_edits) self.cancelEditsButton.clicked.connect(self.model.cancel_edits) def _setupUi(self): self.mainLayout = QVBoxLayout(self) self.buttonLayout = QGridLayout() self.normalButton = QPushButton("Normal") self.buttonLayout.addWidget(self.normalButton, 0, 0) self.titleButton = QPushButton("Title") self.buttonLayout.addWidget(self.titleButton, 1, 0) self.footnoteButton = QPushButton("Footnote") self.buttonLayout.addWidget(self.footnoteButton, 2, 0) self.ignoreButton = QPushButton("Ignore") self.buttonLayout.addWidget(self.ignoreButton, 0, 1) self.tofixButton = QPushButton("To Fix") self.buttonLayout.addWidget(self.tofixButton, 1, 1) self.mainLayout.addLayout(self.buttonLayout) self.rightLayout = QVBoxLayout() self.hideIgnoredCheckBox = QCheckBox("Hide Ignored Elements") self.rightLayout.addWidget(self.hideIgnoredCheckBox) self.textEdit = QTextEdit() self.textEdit.setAcceptRichText(False) self.rightLayout.addWidget(self.textEdit) self.editButtonLayout = QHBoxLayout() self.editButtonLayout.addItem(horizontalSpacer()) self.saveEditsButton = QPushButton("Save") self.editButtonLayout.addWidget(self.saveEditsButton) self.cancelEditsButton = QPushButton("Cancel") self.editButtonLayout.addWidget(self.cancelEditsButton) self.rightLayout.addLayout(self.editButtonLayout) self.mainLayout.addLayout(self.rightLayout) #--- Signals def hideIgnoredCheckBoxStateChanged(self, state): self.model.app.hide_ignored = state == Qt.Checked def textEditTextChanged(self): self.model.edit_text = self.textEdit.toPlainText() #--- model -> view def refresh_edit_text(self): self.textEdit.setText(self.model.edit_text) self.textEdit.setEnabled(self.model.edit_enabled) self.saveEditsButton.setEnabled(self.model.edit_enabled) self.cancelEditsButton.setEnabled(self.model.edit_enabled)
def _setupUi(self): self.mainLayout = QVBoxLayout(self) self.buttonLayout = QGridLayout() self.normalButton = QPushButton("Normal") self.buttonLayout.addWidget(self.normalButton, 0, 0) self.titleButton = QPushButton("Title") self.buttonLayout.addWidget(self.titleButton, 1, 0) self.footnoteButton = QPushButton("Footnote") self.buttonLayout.addWidget(self.footnoteButton, 2, 0) self.ignoreButton = QPushButton("Ignore") self.buttonLayout.addWidget(self.ignoreButton, 0, 1) self.tofixButton = QPushButton("To Fix") self.buttonLayout.addWidget(self.tofixButton, 1, 1) self.mainLayout.addLayout(self.buttonLayout) self.rightLayout = QVBoxLayout() self.hideIgnoredCheckBox = QCheckBox("Hide Ignored Elements") self.rightLayout.addWidget(self.hideIgnoredCheckBox) self.textEdit = QTextEdit() self.textEdit.setAcceptRichText(False) self.rightLayout.addWidget(self.textEdit) self.editButtonLayout = QHBoxLayout() self.editButtonLayout.addItem(horizontalSpacer()) self.saveEditsButton = QPushButton("Save") self.editButtonLayout.addWidget(self.saveEditsButton) self.cancelEditsButton = QPushButton("Cancel") self.editButtonLayout.addWidget(self.cancelEditsButton) self.rightLayout.addLayout(self.editButtonLayout) self.mainLayout.addLayout(self.rightLayout)
def setColorColumn(self): self.color_list = self.color_list[0:self.num_buckets] for i in range(self.num_buckets): colorPB = QPushButton() colorPB.setStyleSheet("QPushButton { background-color: %s; margin: 1px; border: 0px; }" % self.color_list[i]) colorPB.connect(colorPB, SIGNAL('clicked()'), self.makeChooseColor(colorPB,i)) self.tbl_Colors.setCellWidget(i,0,colorPB)
def addLabelClass(self, label_config): # Check label configuration if 'attributes' not in label_config: raise ImproperlyConfigured("Label with no 'attributes' dict found") attrs = label_config['attributes'] if 'class' not in attrs: raise ImproperlyConfigured("Labels must have an attribute 'class'") label_class = attrs['class'] if label_class in self._class_config: raise ImproperlyConfigured("Label with class '%s' defined more than once" % label_class) # Store config self._class_config[label_class] = label_config # Parse configuration and create handlers and item self.parseConfiguration(label_class, label_config) # Add label class button button = QPushButton(label_class, self) button.setCheckable(True) button.setFlat(True) button.clicked.connect(bind(self.onClassButtonPressed, label_class)) self._class_buttons[label_class] = button self._classbox_layout.addWidget(button) # Add hotkey if 'hotkey' in label_config: hotkey = QShortcut(QKeySequence(label_config['hotkey']), self) hotkey.activated.connect(button.click) self._class_shortcuts[label_class] = hotkey
def initUI(self): self.mainLayout = QGridLayout(self) self.groupA = None lblSegConfig = QLabel('Select label') self.mainLayout.addWidget(lblSegConfig, 1, 1, 1, 6) self.initLabels() btnLabel = QPushButton("New label") btnLabel.setCheckable(True) btnLabel.clicked.connect(self.btnNewLabel) self.mainLayout.addWidget(btnLabel, 1, 3, 1, 2) lblSegType = QLabel('Choose type of segmentation') self.mainLayout.addWidget(lblSegType, 4, 1, 1, 6) lblSegType = QLabel('Choose virtual resection') self.mainLayout.addWidget(lblSegType, 6, 1, 1, 6) self.initConfigs() self.lblSegData = QLabel() self.mainLayout.addWidget(self.lblSegData, 8, 1, 1, 6) self.lblSegError = QLabel() self.lblSegError.setStyleSheet("color: red;"); self.mainLayout.addWidget(self.lblSegError, 9, 1, 1, 6)
def setModel(self, model): super( DataLaneSummaryTableView, self ).setModel(model) self._retained = [] roleIndex = 0 for column in range( LaneColumn.NumColumns, model.columnCount(), DatasetInfoColumn.NumColumns ): menu = QMenu(parent=self) menu.setObjectName( "SummaryTable_AddButton_{}".format( roleIndex ) ) self._retained.append(menu) menu.addAction( "Add File(s)..." ).triggered.connect( partial(self.addFilesRequested.emit, roleIndex) ) menu.addAction( "Add Volume from Stack..." ).triggered.connect( partial(self.addStackRequested.emit, roleIndex) ) menu.addAction( "Add Many by Pattern..." ).triggered.connect( partial(self.addByPatternRequested.emit, roleIndex) ) button = QPushButton("Add File(s)...", self) button.setMenu( menu ) self.addFilesButtons[roleIndex] = button lastRow = self.model().rowCount()-1 modelIndex = self.model().index( lastRow, column ) self.setIndexWidget( modelIndex, button ) roleIndex += 1 # TODO: Implement support for the labelable flag again... self.setColumnHidden(LaneColumn.LabelsAllowed, True)
def __init__(self, parent=None): super(NotebookListDialog, self).__init__(parent) self.notebookList = QListWidget() self.moveUp = QPushButton('<<') self.moveDown = QPushButton('>>') self.add = QPushButton('Add') self.remove = QPushButton('Remove') self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False) layout = QGridLayout() layout.addWidget(self.notebookList, 0, 0, 4, 6) layout.addWidget(self.moveUp, 1, 6) layout.addWidget(self.moveDown, 2, 6) layout.addWidget(self.add, 4, 0) layout.addWidget(self.remove, 4, 1) layout.addWidget(self.buttonBox, 4, 5, 1, 2) self.setLayout(layout) self.notebookList.setItemDelegate(ListDelegate(self.notebookList)) self.notebookList.currentRowChanged.connect(self.updateUi) self.add.clicked.connect(self.actionAdd) self.remove.clicked.connect(self.actionRemove) self.moveUp.clicked.connect(self.moveItemUp) self.moveDown.clicked.connect(self.moveItemDown) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.initList()
def __init__(self, param, table): QDialog.__init__(self) self.setupUi(self) self.tblView.setSelectionBehavior(QAbstractItemView.SelectRows) self.tblView.setSelectionMode(QAbstractItemView.ExtendedSelection) self.param = param self.rettable = None # Additional buttons self.btnAdd = QPushButton(self.tr('Add row')) self.buttonBox.addButton(self.btnAdd, QDialogButtonBox.ActionRole) self.btnRemove = QPushButton(self.tr('Remove row(s)')) self.buttonBox.addButton(self.btnRemove, QDialogButtonBox.ActionRole) self.btnRemoveAll = QPushButton(self.tr('Remove all')) self.buttonBox.addButton(self.btnRemoveAll, QDialogButtonBox.ActionRole) self.btnAdd.clicked.connect(self.addRow) self.btnRemove.clicked.connect(lambda: self.removeRows()) self.btnRemoveAll.clicked.connect(lambda: self.removeRows(True)) if not self.param.fixedNumOfRows: self.btnAdd.setEnabled(False) self.btnRemove.setEnabled(False) self.btnRemoveAll.setEnabled(False) self.populateTable(table)
def __init__(self, parent): QDialog.__init__(self, parent, Qt.Dialog) self.setWindowTitle(self.tr("Plugins Manager")) self.setModal(True) self.resize(700, 500) vbox = QVBoxLayout(self) self._tabs = QTabWidget() vbox.addWidget(self._tabs) btnReload = QPushButton(self.tr("Reload")) btnReload.setMaximumWidth(100) vbox.addWidget(btnReload) self.overlay = ui_tools.Overlay(self) self.overlay.hide() self._oficial_available = [] self._community_available = [] self._locals = [] self._updates = [] self._loading = True self.connect(btnReload, SIGNAL("clicked()"), self._reload_plugins) self.thread = ThreadLoadPlugins(self) self.connect(self.thread, SIGNAL("finished()"), self._load_plugins_data) self.connect(self.thread, SIGNAL("plugin_downloaded(PyQt_PyObject)"), self._after_download_plugin) self.connect(self.thread, SIGNAL("plugin_uninstalled(PyQt_PyObject)"), self._after_uninstall_plugin) self.overlay.show() self._reload_plugins()
def show_tx_qrcode(self, data, title): if not data: return d = QDialog(self.gui) d.setModal(1) d.setWindowTitle(title) d.setMinimumSize(250, 525) vbox = QVBoxLayout() qrw = QRCodeWidget(data) vbox.addWidget(qrw, 0) hbox = QHBoxLayout() hbox.addStretch(1) def print_qr(self): filename = "qrcode.bmp" electrum_gui.bmp.save_qrcode(qrw.qr, filename) QMessageBox.information(None, _('Message'), _("QR code saved to file") + " " + filename, _('OK')) b = QPushButton(_("Save")) hbox.addWidget(b) b.clicked.connect(print_qr) b = QPushButton(_("Close")) hbox.addWidget(b) b.clicked.connect(d.accept) b.setDefault(True) vbox.addLayout(hbox, 1) d.setLayout(vbox) d.exec_()
def add_push_button(self, name='test', fulldesc='This is a Test', advance_n=True, text_font=ARIAL_12B, col=0, connect_function=None, background='', pressed_bgrnd='', parent=None, layout=None): # springgreen #00FF7F , lightgreen #90EE90 , powderblue #B0E0E6 # if parent is input, add widget to parent if parent is None: parent = self if layout is None: NRow = parent.get_next_row_number(advance_n) btn = QPushButton(fulldesc, parent) btn.setFont( text_font ) if background and pressed_bgrnd: btn.setStyleSheet("QPushButton { background-color:%s } "%background +\ "QPushButton:pressed { background-color: %s }"%pressed_bgrnd ) if layout is None: parent.grid.addWidget(btn, NRow, col) else: layout.addWidget( btn ) self.objectD['%s_push_btn'%name] = btn self.input_widget_by_nameD[name] = (btn , 'push_btn') if connect_function is not None: btn.clicked.connect( connect_function )
def __init__(self, parent, available): QWidget.__init__(self, parent) self._parent = parent self._available = available vbox = QVBoxLayout(self) self._table = QTableWidget(1, 5) self._table.removeRow(0) vbox.addWidget(self._table) self._headers = ('Name', 'Version', 'Description', "Authors", "Web") ui_tools.load_table(self._table, self._headers, _format_for_table(available)) self._table.setColumnWidth(0, 200) hbox = QHBoxLayout() btnInstall = QPushButton('Install') btnInstall.setMaximumWidth(100) hbox.addWidget(btnInstall) hbox.addWidget(QLabel(self.tr("NINJA needs to be restarted for " \ "changes to take effect."))) vbox.addLayout(hbox) # hbox = QHBoxLayout() # hbox.addWidget(QLabel( # self.tr("Add an external Plugin. URL Zip File:"))) # self._link = QLineEdit() # hbox.addWidget(self._link) # btnAdd = QPushButton(self.tr("Add")) # hbox.addWidget(btnAdd) # vbox.addLayout(hbox) # lblExternalPlugin = QLabel( # self.tr("(Write the URL of the Plugin and press 'Add')")) # lblExternalPlugin.setAlignment(Qt.AlignRight) # vbox.addWidget(lblExternalPlugin) self.connect(btnInstall, SIGNAL("clicked()"), self._install_plugins)
def __init__(self): super(HistoryDialog, self).__init__(None) self.setupUi(self) self.groupIcon = QIcon() self.groupIcon.addPixmap(self.style().standardPixmap( QStyle.SP_DirClosedIcon), QIcon.Normal, QIcon.Off) self.groupIcon.addPixmap(self.style().standardPixmap( QStyle.SP_DirOpenIcon), QIcon.Normal, QIcon.On) self.keyIcon = QIcon() self.keyIcon.addPixmap(self.style().standardPixmap(QStyle.SP_FileIcon)) self.clearButton = QPushButton(self.tr('Clear')) self.clearButton.setToolTip(self.tr('Clear history and log')) self.buttonBox.addButton(self.clearButton, QDialogButtonBox.ActionRole) self.saveButton = QPushButton(self.tr('Save As...')) self.saveButton.setToolTip(self.tr('Save history and log')) self.buttonBox.addButton(self.saveButton, QDialogButtonBox.ActionRole) self.tree.doubleClicked.connect(self.executeAlgorithm) self.tree.currentItemChanged.connect(self.changeText) self.clearButton.clicked.connect(self.clearLog) self.saveButton.clicked.connect(self.saveLog) self.tree.setContextMenuPolicy(Qt.CustomContextMenu) self.tree.customContextMenuRequested.connect(self.showPopupMenu) self.fillTree()
def __init__(self, parent, color=None): QPushButton.__init__(self, parent) self.parent = parent self.setColor(color) self.clicked.connect(self.onClick) self.setMinimumSize(QSize(25, 25)) self.setMaximumSize(QSize(25, 25))
def __init__(self, parent): VDialog.__init__(self, parent) self.resize(450, 150) self.gLayout = QGridLayout(self) self.mesaj = QLabel(self) self.gLayout.addWidget(self.mesaj, 0, 0, 1, 3) self.pSil = QPushButton(self) self.pSil.setMinimumSize(100, 0) self.pSil.setMaximumSize(100, 25) self.gLayout.addWidget(self.pSil, 1, 0, 1, 1) self.pBirak = QPushButton(self) self.pBirak.setMinimumSize(100, 0) self.pBirak.setMaximumSize(100, 25) self.gLayout.addWidget(self.pBirak, 1, 2, 1, 1) self.pKarantina = QPushButton(self) self.pKarantina.setMinimumSize(100, 0) self.pKarantina.setMaximumSize(100, 25) self.gLayout.addWidget(self.pKarantina, 1, 1, 1, 1) self.pBirak.clicked.connect(self.birak) self.pKarantina.clicked.connect(self.karantina) self.pSil.clicked.connect(self.sil) self.setWindowTitle(u"Virüs Bulundu!") self.mesaj.setText(u"Zmanorka 816 Torsis B bulundu. İkinci derece tehlikleli bir trojan.<br>Sileyim mi, karantinaya mı alayım, bırakayım gitsin mi?") self.pSil.setText(u"Sil") self.pBirak.setText(u"Bırak Gitsin") self.pKarantina.setText(u"Karantinaya Al")
class DuplicateDistanceDialog(QDialog): def __init__(self, isComplexPolygon): """ Constructor :param isComplexPolygon: for a polygon, if it has interior ring(s) """ QDialog.__init__(self) self.setWindowTitle(QCoreApplication.translate("VDLTools","Duplicate")) self.resize(300, 100) self.__distanceLabel = QLabel(QCoreApplication.translate("VDLTools","distance :")) self.__distanceLabel.setMinimumHeight(20) self.__distanceLabel.setMinimumWidth(50) self.__distanceEdit = QLineEdit("inputMask") self.__distanceEdit.setMinimumHeight(20) self.__distanceEdit.setMinimumWidth(120) self.__distanceEdit.setValidator(QDoubleValidator(-1000, 1000, 4, self)) self.__distanceDirection = QCheckBox(QCoreApplication.translate("VDLTools","invert direction")) self.__previewButton = QPushButton(QCoreApplication.translate("VDLTools","Preview")) self.__previewButton.setMinimumHeight(20) self.__previewButton.setMinimumWidth(100) self.__okButton = QPushButton(QCoreApplication.translate("VDLTools","OK")) self.__okButton.setMinimumHeight(20) self.__okButton.setMinimumWidth(100) self.__cancelButton = QPushButton(QCoreApplication.translate("VDLTools","Cancel")) self.__cancelButton.setMinimumHeight(20) self.__cancelButton.setMinimumWidth(100) self.__layout = QGridLayout() self.__layout.addWidget(self.__distanceLabel, 0, 0) self.__layout.addWidget(self.__distanceEdit, 0, 1) self.__layout.addWidget(self.__distanceDirection, 0, 2) if isComplexPolygon: self.__polygonLabel = QLabel( QCoreApplication.translate("VDLTools","In which direction the internal part has to be duplicated ?")) self.__polygonLabel.setMinimumHeight(20) self.__polygonLabel.setMinimumWidth(50) self.__layout.addWidget(self.__polygonLabel, 1, 0, 1, 3) self.__directions = [QRadioButton(QCoreApplication.translate("VDLTools","same")), QRadioButton(QCoreApplication.translate("VDLTools","opposite"))] self.__directions[0].setChecked(True) self.__direction_button_group = QButtonGroup() for i in xrange(len(self.__directions)): self.__layout.addWidget(self.__directions[i], 2, i+1) self.__direction_button_group.addButton(self.__directions[i], i) self.__layout.addWidget(self.__previewButton, 3, 0) self.__layout.addWidget(self.__okButton, 3, 1) self.__layout.addWidget(self.__cancelButton, 3, 2) self.setLayout(self.__layout) def previewButton(self): """ To get the preview button instance :return: preview button instance """ return self.__previewButton def okButton(self): """ To get the ok button instance :return: ok button instance """ return self.__okButton def cancelButton(self): """ To get the cancel button instance :return: cancel button instance """ return self.__cancelButton def distanceEdit(self): """ To get the distance edit widget :return: distance edit widget """ return self.__distanceEdit def directionCheck(self): return self.__distanceDirection def distanceEditText(self): """ To get the text putted into the distance edit field :return: text from ditance edit field """ return self.__distanceEdit.text() def setDistanceEditText(self, text): """ To set the distance displayed in the distance edit field """ self.__distanceEdit.setText(text) def isInverted(self): """ To get if the user want a complex polygon duplication inverted or not :return: true if inverted, false otherwise """ return self.__direction_button_group.checkedId() == 1
def __init__(self, message='', logInText='LoginWindow.logIn', cancelText='cancel'): super().__init__() self._canceled = False self._ready = False logInButton = QPushButton(_(logInText)) logInButton.clicked.connect(self._store_results) logInButton.setDefault(True) cancelButton = QPushButton(_(cancelText)) cancelButton.clicked.connect(self._cancel) buttonBox = QHBoxLayout() buttonBox.addStretch(1) buttonBox.addWidget(cancelButton) buttonBox.addWidget(logInButton) self.serverInput = QLineEdit(self) self.serverInput.setPlaceholderText(_('LoginWindow.server')) self.serverInput.setToolTip(_('LoginWindow.serverToolTip')) self.dbInput = QLineEdit(self) self.dbInput.setPlaceholderText(_('LoginWindow.database')) self.dbInput.setToolTip(_('LoginWindow.databaseToolTip')) self.userInput = QLineEdit(self) self.userInput.setPlaceholderText(_('LoginWindow.user')) self.userInput.setToolTip(_('LoginWindow.userToolTip')) self.passInput = QLineEdit(self) self.passInput.setPlaceholderText(_('LoginWindow.password')) self.passInput.setToolTip(_('LoginWindow.passwordToolTip')) self.passInput.setEchoMode(QLineEdit.Password) self.autoLogin = QCheckBox() self.autoLogin.setText(_('LoginWindow.autoLogin')) self.autoLogin.toggled.connect(self._set_auto) self.serverInput.setText(get('Login', 'host')) self.dbInput.setText(get('Login', 'database')) self.userInput.setText(get('Login', 'user')) if not self.serverInput.text(): self.serverInput.setFocus() elif not self.dbInput.text(): self.dbInput.setFocus() elif not self.userInput.text(): self.userInput.setFocus() else: self.passInput.setFocus() if message: self.errorLabel = QLabel(_(message)) palette = QPalette() palette.setColor(QPalette.Foreground, Qt.red) self.errorLabel.setPalette(palette) inputBox = QVBoxLayout() if message: inputBox.addWidget(self.errorLabel) inputBox.addWidget(self.serverInput) inputBox.addWidget(self.dbInput) inputBox.addWidget(self.userInput) inputBox.addWidget(self.passInput) inputBox.addWidget(self.autoLogin) winLayout = QVBoxLayout() winLayout.addLayout(inputBox) winLayout.addLayout(buttonBox) self.setLayout(winLayout) self.setWindowTitle(_('LoginWindow.title')) self.resize(250, 200) self._center()
class WellExportDialog(QDialog): def __init__(self): super(WellExportDialog, self).__init__() self.resize(400, 300) self.initUI() self.export_Button.clicked.connect(self.export_well) self.button_box.rejected.connect(self.close) self.select_Button.clicked.connect(self.select_file) self.well_comboBox.currentIndexChanged.connect( self.populate_log_listWidget) self.update_well_comboBox() def initUI(self): self.setWindowIcon(QIcon(':/icon/export')) self.setWindowTitle("Export Well") self.layout = QGridLayout(self) # add QLabel self.label_0 = QLabel(self) self.label_0.setGeometry(QRect(0, 24, 31, 20)) self.label_0.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter) self.label_0.setText("Well to export:") self.layout.addWidget(self.label_0, 0, 0) # add QComboBox self.well_comboBox = QComboBox(self) self.well_comboBox.setGeometry(QRect(10, 10, 101, 24)) self.layout.addWidget(self.well_comboBox, 0, 1, 1, 1) # add QCheckBox self.checkbox = QCheckBox(self) self.checkbox.setText("Full LAS") self.checkbox.setCheckState(Qt.Unchecked) self.layout.addWidget(self.checkbox, 0, 2) # add QListWidget self.logs_listWidget = QListWidget(self) self.logs_listWidget.setGeometry(QRect(0, 0, 101, 201)) # self.well_comboBox.setMaximumHeight(151) self.layout.addWidget(self.logs_listWidget, 1, 1) # add QLabel self.label_1 = QLabel(self) self.label_1.setGeometry(QRect(0, 24, 31, 20)) self.label_1.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter) self.label_1.setText("Output File:") self.layout.addWidget(self.label_1, 2, 0) # add QLineEdit self.file_path_lineEdit = QLineEdit(self) self.file_path_lineEdit.setGeometry(QRect(50, 24, 81, 20)) self.layout.addWidget(self.file_path_lineEdit, 2, 1) # add Button self.select_Button = QPushButton(self) self.select_Button.setMaximumSize(QSize(61, 24)) self.select_Button.setText("Select") self.layout.addWidget(self.select_Button, 2, 2) # add QDialogButtonBox self.button_box = QDialogButtonBox(self) self.export_Button = self.button_box.addButton( "Export", QDialogButtonBox.ApplyRole) self.button_box.addButton(QDialogButtonBox.Cancel) self.layout.addWidget(self.button_box, 3, 0, 1, 3) def update_well_comboBox(self): survey_file = CONF.survey_dir / '.survey' if survey_file.exists(): dnames = get_data_files(CONF.well_dir) self.well_comboBox.addItems(dnames) def populate_log_listWidget(self): self.logs_listWidget.clear() well = ppp.Well( str(CONF.well_dir / ".{}".format(self.well_comboBox.currentText()))) # self.logs_listWidget.addItems(well.logs) for name in well.logs: new_item = QListWidgetItem(name, self.logs_listWidget) new_item.setFlags(new_item.flags() | Qt.ItemIsUserCheckable) new_item.setCheckState(Qt.Unchecked) def export_well(self): file_name = str(self.file_path_lineEdit.text()) if not file_name: QMessageBox().information(self, "Info", "Please select ouput file.") pass else: well = well = ppp.Well( str(CONF.well_dir / ".{}".format(self.well_comboBox.currentText()))) logs_to_export = [] for i in range(self.logs_listWidget.count()): item = self.logs_listWidget.item(i) if item.checkState() == Qt.Checked: logs_to_export.append(str(item.text())) full = True if self.checkbox.checkState() == Qt.Checked \ else False well.export(file_name, logs_to_export, full) QMessageBox().information(self, "Info", "Succeed!") def select_file(self): fl = QFileDialog.getSaveFileName(self, 'Save File', str(CONF.well_dir)) self.file_path_lineEdit.setText(fl)
class LoadVfkPuWidget(PuWidget): """A widget for loading a VFK file.""" set_text_statusbar = pyqtSignal(str, int, bool) set_text_browseVfkLineEdit = pyqtSignal(str) set_value_loadVfkProgressBar = pyqtSignal(int) def _setup_self(self): """Sets up self.""" self.setObjectName(u'loadVfkPuWidget') self.gridLayout = QGridLayout(self) self.gridLayout.setObjectName(u'gridLayout') self._build_widgets() def _build_widgets(self): """Builds own widgets.""" self.set_text_statusbar.connect(self.dW.statusBar.set_text) self.set_text_statusbar.emit(u'Vyberte VFK soubor.', 0, False) self.browseVfkLabel = QLabel(self) self.browseVfkLabel.setObjectName(u'browseVfkLabel') self.browseVfkLabel.setText(u'VFK soubor:') self.gridLayout.addWidget(self.browseVfkLabel, 0, 0, 1, 1) self.browseVfkLineEdit = QLineEdit(self) self.browseVfkLineEdit.setObjectName(u'browseVfkLineEdit') self.set_text_browseVfkLineEdit.connect( self._set_text_browseVfkLineEdit) self.browseVfkLineEdit.textChanged.connect(self._check_vfk_file_path) self.gridLayout.addWidget(self.browseVfkLineEdit, 0, 1, 1, 1) self.browseVfkPushButton = QPushButton(self) self.browseVfkPushButton.setObjectName(u'browseVfkPushButton') self.browseVfkPushButton.clicked.connect(self._browse_vfk_files) self.browseVfkPushButton.setText(u'Procházet') self.gridLayout.addWidget(self.browseVfkPushButton, 0, 2, 1, 1) self.gridLayout.setRowStretch(1, 1) self.loadVfkProgressBar = QProgressBar(self) self.loadVfkProgressBar.setObjectName(u'loadVfkProgressBar') self.loadVfkProgressBar.setMinimum(0) self.set_value_loadVfkProgressBar.connect( self._set_value_loadVfkProgressBar) self.set_value_loadVfkProgressBar.emit(0) self.gridLayout.addWidget(self.loadVfkProgressBar, 2, 0, 1, 2) self.loadVfkPushButton = QPushButton(self) self.loadVfkPushButton.setObjectName(u'loadVfkPushButton') self.loadVfkPushButton.clicked.connect(self._start_loading_vfk_layer) self.loadVfkPushButton.setText(u'Načíst') self.loadVfkPushButton.setDisabled(True) self.gridLayout.addWidget(self.loadVfkPushButton, 2, 2, 1, 1) def _set_text_browseVfkLineEdit(self, text): """Sets the text to the browseVfkLineEdit. Args: text (str): A text to be set. """ self.browseVfkLineEdit.setText(text) def _set_value_loadVfkProgressBar(self, value): """Sets the value to the loadVfkProgressBar. Args: text (str): A value to be set. """ self.loadVfkProgressBar.setValue(value) def _browse_vfk_files(self): """Opens a file dialog and filters VFK files.""" title = u'Vyberte VFK soubor.' filters = u'.vfk (*.vfk)' filePath = self.dW.open_file_dialog(title, filters, True) if filePath: self.set_text_browseVfkLineEdit.emit(filePath) def _check_vfk_file_path(self): """Checks if the text in the browseVfkLineEdit is a path to a VFK file. If so, the loadVfkPushButton is enabled, otherwise the loadVfkPushButton is disabled. """ tempText = self.browseVfkLineEdit.text() tempFileInfo = QFileInfo(tempText) if tempFileInfo.isFile() and tempFileInfo.suffix() in (u'vfk', u'VFK'): self.loadVfkPushButton.setEnabled(True) else: self.loadVfkPushButton.setEnabled(False) def _start_loading_vfk_layer(self): """Starts loading the selected VFK file in a separate thread.""" self.set_text_statusbar.emit( u'Načítám VFK soubor. Tento proces může chvíli trvat...', 0, False) self._enable_load_widgets(False) filePath = self.browseVfkLineEdit.text() QgsApplication.processEvents() self.loadThread = LoadThread(filePath) self.loadThread.started.connect(self._run_loading_vfk_layer) self.loadThread.start() def _run_loading_vfk_layer(self, filePath): """Calls methods for loading a VFK layer. Disables loading widgets until the loading is finished. Args: filePath (str): A full path to the file. """ try: self.set_value_loadVfkProgressBar.emit(0) fileInfo = QFileInfo(filePath) dbPath = QDir(fileInfo.absolutePath())\ .filePath(fileInfo.completeBaseName() + '.db') layerCode = self.dW.parLayerCode vfkDriverName = 'VFK' layerName = fileInfo.completeBaseName() + '|' + layerCode self._create_db_file(filePath, dbPath, layerCode, vfkDriverName) self._open_database(dbPath) # SpatiaLite fix - start if not self.dW.fixedSqliteDriver: dbPath = self._create_spatialite_db_file(dbPath) # SpatiaLite fix - end self._load_vfk_layer(dbPath, layerName, layerCode, vfkDriverName) self.loadVfkProgressBar.setMaximum(1) self.set_value_loadVfkProgressBar.emit(1) self.set_text_statusbar.emit(u'Data byla úspešně načtena.', 0, False) except self.dW.puError: QgsApplication.processEvents() except: QgsApplication.processEvents() self.dW.display_error_messages( self, u'Error loading VFK file "{}".'.format(filePath), u'Chyba při načítání VFK souboru.', u'Chyba při načítání VFK souboru "{}".'.format(filePath)) finally: QgsApplication.processEvents() self._enable_load_widgets(True) def _create_db_file(self, filePath, dbPath, layerCode, vfkDriverName): """Creates a database file. It checks if a database of the same name as the file exists. If not it creates the database with a VFK driver. Args: filePath (str): A full path to the file. dbPath (str): A full path to the database. layerCode (str): A code of the layer. vfkDriverName (str): A name of the VFK driver. Raises: dw.puError: When the VFK driver failed to open VFK file or when the SQlite driver failed to open the database. """ QgsApplication.processEvents() dbInfo = QFileInfo(dbPath) if not dbInfo.isFile(): self.set_text_statusbar.emit( u'Importuji data do SQLite databáze...', 0, False) QgsApplication.processEvents() QgsApplication.registerOgrDrivers() vfkDriver = ogr.GetDriverByName(vfkDriverName) vfkDataSource = vfkDriver.Open(filePath) QgsApplication.processEvents() if not vfkDataSource: raise self.dW.puError( self.dW, self, u'Failed to load data, "{}" is not a valid VFK datasource.' .format(dbPath), u'Data nelze načíst.', u'Data nelze načíst, "{}" není platný datový zdroj VFK.'. format(dbPath)) layerCount, layerNames = self._check_layer_code( vfkDataSource, layerCode) self.loadVfkProgressBar.setMaximum(layerCount) for i in xrange(layerCount): self.set_value_loadVfkProgressBar.emit(i + 1) self.set_text_statusbar.emit( u'Načítám vrstvu {} ({}/{})...'.format( layerNames[i], i + 1, layerCount), 0, False) QgsApplication.processEvents() self._build_geometry(layerCode, vfkDataSource) QgsApplication.processEvents() for vertexLayerCode in self.dW.vertexLayerCodes: if vertexLayerCode in layerNames: self._build_geometry(vertexLayerCode, vfkDataSource) QgsApplication.processEvents() vfkDataSource.Destroy() sqliteDriver = ogr.GetDriverByName('SQLite') sqliteDataSource = sqliteDriver.Open(dbPath) if not sqliteDataSource: raise self.dW.puError( self.dW, self, u'Failed to load data, "{}" is not a valid SQLite datasource.'. format(dbPath), u'Data nelze načíst.', u'Data nelze načíst, "{}" není platný datový zdroj SQLite.'. format(dbPath)) layerCount, layerNames = self._check_layer_code( sqliteDataSource, layerCode) sqliteDataSource.Destroy() def _check_layer_code(self, dataSource, layerCode): """Checks if there is a layer code layer in the data source. Args: dataSource (osgeo.ogr.DataSource): A data source. layerCode (str): A code of the layer. Returns: int: A number of layers in the data source. list: A list of layer names in the data source. Raises: dw.puError: When there is no layer code layer in the data source. """ layerCount = dataSource.GetLayerCount() layerNames = [] for i in xrange(layerCount): layerNames.append(dataSource.GetLayer(i).GetLayerDefn().GetName()) if layerCode not in layerNames: QgsApplication.processEvents() dataSource.Destroy() raise self.dW.puError( self.dW, self, u'VFK file does not contain "{}" layer, therefore it can not be ' u'loaded by PU Plugin. The file can be ' u'loaded by "Add Vector Layer"'.format(layerCode), u'VFK soubor neobsahuje vrstvu {}.'.format(layerCode), u'VFK soubor neobsahuje vrstvu {}, proto nemůže být ' u'pomocí PU Pluginu načten. Data je možné načíst ' u'pomocí "Přidat vektorovou vrstvu."'.format(layerCode)) dataSourceInfo = (layerCount, layerNames) return dataSourceInfo def _build_geometry(self, layerCode, dataSource): """Builds a geometry for the layer in the data source.. Args: layerCode (str): A code of the layer. dataSource (ogr.DataSource) A reference to the OGR data source. """ codeLayer = dataSource.GetLayerByName(layerCode) codeLayer.GetFeatureCount(True) for feature in codeLayer: feature.GetGeometryRef() def _open_database(self, dbPath): """Opens a database. Checks if there are geometry_columns and spatial_ref_sys tables in the database, if not it creates and fills those tables. Checks if there are all PU columns in PAR table, if it it creates and fills those columns. Args: dbPath (str): A full path to the database. Raises: dw.puError: When SQLITE database driver is not available or when database connection fails. """ if not QSqlDatabase.isDriverAvailable('QSQLITE'): raise self.dW.puError( self.dW, self, u'SQLITE database driver is not available.', u'Databázový ovladač QSQLITE není dostupný.', u'Databázový ovladač QSQLITE není dostupný.') connectionName = QUuid.createUuid().toString() db = QSqlDatabase.addDatabase('QSQLITE', connectionName) db.setDatabaseName(dbPath) db.open() if not db.open(): raise self.dW.puError(self.dW, self, u'Database connection failed.', u'Nepodařilo se připojit k databázi.', u'Nepodařilo se připojit k databázi.') self.set_text_statusbar.emit(u'Kontroluji tabulky a sloupce...', 0, False) QgsApplication.processEvents() sqlQuery = QSqlQuery(db) sqlDir = QDir(self.pluginDir.path() + u'/data/sql') query = self._read_text_from_file(sqlDir.filePath(u'check_gc_srs.sql')) sqlQuery.exec_(query) QgsApplication.processEvents() checkGcSrsSize = 0 while sqlQuery.next(): checkGcSrsSize += 1 if checkGcSrsSize < 2: queries = self._read_text_from_file( sqlDir.filePath(u'create_fill_gc_srs.sql')).split(';') for query in queries: sqlQuery.exec_(query) QgsApplication.processEvents() query = self._read_text_from_file( sqlDir.filePath(u'check_pu_columns_PAR.sql')) sqlQuery.exec_(query) QgsApplication.processEvents() columns = [] while sqlQuery.next(): record = sqlQuery.record() name = str(record.value('name')) columns.append(name) if not all(column in columns for column in self.dW.allPuColumns): queries = self._read_text_from_file( sqlDir.filePath(u'add_pu_columns_PAR.sql')).split(';') for query in queries: sqlQuery.exec_(query) QgsApplication.processEvents() queries = self._read_text_from_file( sqlDir.filePath(u'create_sobr_spol.sql')).split(';') for query in queries: sqlQuery.exec_(query) db.close() def _create_spatialite_db_file(self, dbPath): """Creates a SpatiaLite database file. Args: dbPath (str): A full path to the database. Returns: dbPath (str): A full path to the SpatiaLite database. """ dbInfo = QFileInfo(dbPath) sdbPath = QDir(dbInfo.absolutePath())\ .filePath(dbInfo.completeBaseName() + '.sdb') sdbInfo = QFileInfo(sdbPath) if not sdbInfo.isFile(): self.set_text_statusbar.emit( u'Importuji data do SpatiaLite databáze...', 0, False) QgsApplication.processEvents() sqliteDriver = ogr.GetDriverByName('SQLite') spatialiteDataSource = sqliteDriver.CreateDataSource( sdbPath, ['SPATIALITE=YES']) sqliteDataSource = ogr.Open(dbPath) for layerCode in ( self.dW.parLayerCode, ) + self.dW.vertexLayerCodes: originalLayer = sqliteDataSource.GetLayerByName(layerCode) copiedLayer = spatialiteDataSource.CopyLayer( originalLayer, layerCode, ['LAUNDER=NO']) sqliteDataSource.Destroy() spatialiteDataSource.Destroy() QgsApplication.processEvents() return sdbPath def _read_text_from_file(self, filePath, maxSize=2000): """Reads a text from the given file. Args: filePath (str): A full path to the file. maxSize (int): Maximum size of read data from the file in bytes. Returns: str: The text from the file. """ file = QFile(filePath) file.open(QFile.ReadOnly | QFile.Text) text = file.readData(maxSize) file.close() return text def _load_vfk_layer(self, dbPath, layerName, layerCode, vfkDriverName): """Loads a layer of the given code from database into the map canvas. Args: dbPath (str): A full path to the database. layerName (str): A name of the layer. layerCode (str): A code of the layer. vfkDriverName (str): A name of the VFK driver. Raises: dw.puError: When layerCode layer is not valid. """ self.set_text_statusbar.emit( u'Přidávám vrstvu {}...'.format(layerCode), 0, False) QgsApplication.processEvents() # SpatiaLite fix - start if not self.dW.fixedSqliteDriver: composedURI = QgsDataSourceURI() composedURI.setDatabase(dbPath) schema = '' table = layerCode geometryColumn = 'GEOMETRY' composedURI.setDataSource(schema, table, geometryColumn) layer = QgsVectorLayer(composedURI.uri(), layerName, 'spatialite') else: blacklistedDriver = ogr.GetDriverByName(vfkDriverName) blacklistedDriver.Deregister() composedURI = dbPath + '|layername=' + layerCode layer = QgsVectorLayer(composedURI, layerName, 'ogr') blacklistedDriver.Register() # SpatiaLite fix - end if layer.isValid(): self._set_scale_for_features_with_no_or_invalid_geometry(layer) self.dW.set_layer_style(layer, layerCode) self._set_layer_form_config(layer) self._set_layer_table_config(layer) QgsMapLayerRegistry.instance().addMapLayer(layer) self._set_layer_snapping(layer) QgsApplication.processEvents() else: raise self.dW.puError(self.dW, self, u'Layer {} is not valid.'.format(layerCode), u'Vrstva {} není platná.'.format(layerCode), u'Vrstva {} není platná.'.format(layerCode)) def _set_scale_for_features_with_no_or_invalid_geometry(self, layer): """Sets basis scale to zero for features with no or invalid geometry. Args: layer (QgsVectorLayer): A reference to the layer. """ expression = QgsExpression("$geometry is null") features = layer.getFeatures(QgsFeatureRequest(expression)) self.dW.set_field_value_for_features(layer, features, self.dW.puBasisScaleColumnName, 0) def _set_layer_form_config(self, layer): """Sets layer form config. Args: layer (QgsVectorLayer): A reference to the layer. """ fields = layer.pendingFields() formConfig = layer.editFormConfig() for i in layer.pendingAllAttributesList(): if fields[i].name() not in self.dW.editablePuColumns: formConfig.setReadOnly(i) formConfig.setWidgetType(i, 'Hidden') def _set_layer_table_config(self, layer): """Sets layer table config. Args: layer (QgsVectorLayer): A reference to the layer. """ fields = layer.pendingFields() tableConfig = layer.attributeTableConfig() tableConfig.update(fields) columns = tableConfig.columns() for column in columns: if column.name not in self.dW.allVisibleColumns: column.hidden = True tableConfig.setColumns(columns) layer.setAttributeTableConfig(tableConfig) def _set_layer_snapping(self, layer): """Sets layer snapping. Args: layer (QgsVectorLayer): A reference to the layer. """ project = QgsProject.instance() project.setTopologicalEditing(True) project.writeEntry('Digitizing', 'SnappingMode', 'advanced') project.writeEntry('Digitizing', 'IntersectionSnapping', Qt.Checked) project.setSnapSettingsForLayer(layer.id(), True, 2, 1, 10, True) def _enable_load_widgets(self, enableBool): """Sets loading widgets enabled or disabled. Sets enabled or disabled following widgets: browseVfkLineEdit browseVfkPushButton loadVfkPushButton Args: enableBool (bool): True to set enabled, False to set disabled. """ self.browseVfkLineEdit.setEnabled(enableBool) self.browseVfkPushButton.setEnabled(enableBool) self.loadVfkPushButton.setEnabled(enableBool)
class MigrationWidget(QDialog): """2to3 Migration Assistance Widget Class""" def __init__(self, parent=None): super(MigrationWidget, self).__init__(parent, Qt.WindowStaysOnTopHint) self._migration, vbox, hbox = {}, QVBoxLayout(self), QHBoxLayout() lbl_title = QLabel(translations.TR_CURRENT_CODE) lbl_suggestion = QLabel(translations.TR_SUGGESTED_CHANGES) self.current_list, self.suggestion = QListWidget(), QPlainTextEdit() self.suggestion.setReadOnly(True) self.btn_apply = QPushButton(translations.TR_APPLY_CHANGES + " !") self.suggestion.setToolTip(translations.TR_SAVE_BEFORE_APPLY + " !") self.btn_apply.setToolTip(translations.TR_SAVE_BEFORE_APPLY + " !") # pack up all widgets hbox.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding)) hbox.addWidget(self.btn_apply) vbox.addWidget(lbl_title) vbox.addWidget(self.current_list) vbox.addWidget(lbl_suggestion) vbox.addWidget(self.suggestion) vbox.addLayout(hbox) # connections self.connect(self.current_list, SIGNAL("itemClicked(QListWidgetItem*)"), self.load_suggestion) self.connect(self.btn_apply, SIGNAL("clicked()"), self.apply_changes) # registers IDE.register_service('tab_migration', self) ExplorerContainer.register_tab(translations.TR_TAB_MIGRATION, self) def install_tab(self): """Install the Tab on the IDE.""" ide = IDE.get_service('ide') self.connect(ide, SIGNAL("goingDown()"), self.close) def apply_changes(self): """Apply the suggested changes on the Python code.""" lineno = int(self.current_list.currentItem().data(Qt.UserRole)) lines = self._migration[lineno][0].split('\n') remove, code = -1, "" for line in lines: if line.startswith('-'): remove += 1 # line to remove elif line.startswith('+'): code += '{line_to_add}\n'.format(line_to_add=line[1:]) # get and apply changes on editor main_container = IDE.get_service('main_container') if main_container: editorWidget = main_container.get_current_editor() block_start = editorWidget.document().findBlockByLineNumber(lineno) block_end = editorWidget.document().findBlockByLineNumber(lineno + remove) cursor = editorWidget.textCursor() cursor.setPosition(block_start.position()) cursor.setPosition(block_end.position(), QTextCursor.KeepAnchor) cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor) cursor.insertText(code[:-1]) def load_suggestion(self, item): """Take an argument item and load the suggestion.""" lineno, code = int(item.data(Qt.UserRole)), "" lines = self._migration[lineno][0].split('\n') for line in lines: if line.startswith('+'): code += '{line_to_add}\n'.format(line_to_add=line[1:]) self.suggestion.setPlainText(code) main_container = IDE.get_service('main_container') if main_container: editorWidget = main_container.get_current_editor() if editorWidget: editorWidget.jump_to_line(lineno) editorWidget.setFocus() def refresh_lists(self, migration): """Refresh the list of code suggestions.""" self._migration, base_lineno = migration, -1 self.current_list.clear() for lineno in sorted(migration.keys()): linenostr = 'L{line_number}\n'.format(line_number=str(lineno + 1)) data = migration[lineno] lines = data[0].split('\n') if base_lineno == data[1]: continue base_lineno = data[1] message = '' for line in lines: if line.startswith('-'): message += '{line_to_load}\n'.format(line_to_load=line) item = QListWidgetItem(linenostr + message) item.setToolTip(linenostr + message) item.setData(Qt.UserRole, lineno) self.current_list.addItem(item) def clear(self): """Clear the widget.""" self.current_list.clear() self.suggestion.clear() def reject(self): """Reject""" if self.parent() is None: self.emit(SIGNAL("dockWidget(PyQt_PyObject)"), self) def closeEvent(self, event): """Close""" self.emit(SIGNAL("dockWidget(PyQt_PyObject)"), self) event.ignore()
def __init__(self): QWidget.__init__(self) v_box = QVBoxLayout(self) self.setFixedWidth(500) self.settings = QSettings('NINJA-IDE', 'Kunai') #Groups self.gbox_Home = QGroupBox('On Start:') self.gbox_Close = QGroupBox("On Close:") self.gbox_Routes = QGroupBox('Routes:') v_box.addWidget(self.gbox_Home) v_box.addWidget(self.gbox_Close) v_box.addWidget(self.gbox_Routes) self.settings.beginGroup('Preferences') self.settings.beginGroup('General') #Home #Layout v_home = QVBoxLayout() ##CheckBox self.ch_lastSesionFiles = QCheckBox('Load files from last session.') self.ch_lastSesionFiles.setCheckState( self.settings.value('load_files', 2).toInt()[0]) self.ch_activatePlugins = QCheckBox('Activate Plugins.') self.ch_activatePlugins.setCheckState( self.settings.value('activate_plugins', 2).toInt()[0]) self.ch_notifyUpdates = QCheckBox( 'Nofity me for new available updates.') self.ch_notifyUpdates.setCheckState( self.settings.value('notify_updates', 0).toInt()[0]) v_home.addWidget(self.ch_lastSesionFiles) v_home.addWidget(self.ch_activatePlugins) v_home.addWidget(self.ch_notifyUpdates) self.gbox_Home.setLayout(v_home) #Close #Layout v_close = QVBoxLayout() ##CheckBox self.ch_saveState = QCheckBox('Save the window position and geometry.') self.ch_saveState.setCheckState( self.settings.value('save_position_geometry', 0).toInt()[0]) self.ch_confirmExit = QCheckBox('Confirm Exit.') self.ch_confirmExit.setCheckState( self.settings.value('confirm_exit', 2).toInt()[0]) v_close.addWidget(self.ch_saveState) v_close.addWidget(self.ch_confirmExit) self.gbox_Close.setLayout(v_close) #Routes #Layout g_routes = QGridLayout() ##TextBox self.txt_startRoute = QLineEdit() self.txt_startRoute.setText( self.settings.value('start_route', '').toString()) self.txt_projectRoute = QLineEdit() self.txt_projectRoute.setText( self.settings.value('project_route', '').toString()) self.txt_xtraPlugins = QLineEdit() self.txt_xtraPlugins.setText( self.settings.value('extra_plugins_route', '').toString()) ##Button self.btn_startRoute = QPushButton( QIcon(resources.images['openFolder']), '') self.btn_projectRoute = QPushButton( QIcon(resources.images['openFolder']), '') self.btn_xtraPlugins = QPushButton( QIcon(resources.images['openFolder']), '') def load_start_route(): self.txt_startRoute.setText(load_directory(self, 'Start Route')) def load_project_route(): self.txt_projectRoute.setText(load_directory( self, 'Project Route')) def load_xtra_plugins_route(): self.txt_xtraPlugins.setText( load_directory(self, 'Extra Plugins Route')) self.settings.endGroup() #End General Preferences self.settings.endGroup() #Signal self.connect(self.btn_startRoute, SIGNAL('clicked()'), load_start_route) self.connect(self.btn_projectRoute, SIGNAL('clicked()'), load_project_route) self.connect(self.btn_xtraPlugins, SIGNAL('clicked()'), load_xtra_plugins_route) g_routes.addWidget(QLabel('Start Route:'), 0, 0, Qt.AlignRight) g_routes.addWidget(QLabel('Project Files:'), 1, 0, Qt.AlignRight) #g_routes.addWidget(QLabel('Extra Plugins Route:'), 2, 0, Qt.AlignRight) g_routes.addWidget(self.txt_startRoute, 0, 1) g_routes.addWidget(self.txt_projectRoute, 1, 1) #g_routes.addWidget(self.txt_xtraPlugins, 2 ,1) g_routes.addWidget(self.btn_startRoute, 0, 2) g_routes.addWidget(self.btn_projectRoute, 1, 2) #g_routes.addWidget(self.btn_xtraPlugins, 2, 2) self.gbox_Routes.setLayout(g_routes)
def __init__(self, parent): QWidget.__init__(self) v_box = QVBoxLayout(self) self.setFixedWidth(500) self.settings = QSettings('NINJA-IDE', 'Kunai') #groups self.gbox_bars = QGroupBox('Lateral Bars:') self.gbox_fonts = QGroupBox('Fonts:') self.gbox_tabs = QGroupBox('Editor Tabs:') self.gbox_tabsPosition = QGroupBox('Tabs Position:') v_box.addWidget(self.gbox_bars) v_box.addWidget(self.gbox_fonts) v_box.addWidget(self.gbox_tabs) v_box.addWidget(self.gbox_tabsPosition) self.settings.beginGroup('Preferences') self.settings.beginGroup('Interface') #Lateral Bars ##Checks self.ch_simbols = QCheckBox('Show Simbols List.') self.ch_simbols.setCheckState( self.settings.value('show_simbol_list', 2).toInt()[0]) self.ch_files = QCheckBox('Show Files List.') self.ch_files.setCheckState( self.settings.value('show_files_list', 2).toInt()[0]) v_bars = QVBoxLayout() v_bars.addWidget(self.ch_simbols) v_bars.addWidget(self.ch_files) self.gbox_bars.setLayout(v_bars) #Buttons self.btn_editor_font = QPushButton( self.settings.value('editor_font', 'Monospace, 10').toString()) #self.btn_simbol_font = QPushButton(self.settings.value('simbol_list_font','Monospace, 10').toString()) #self.btn_message_font = QPushButton(self.settings.value('window_message_font','Monospace, 10').toString()) def load_editor_font(): self.btn_editor_font.setText( load_font( self, self.get_font_from_string(self.btn_editor_font.text()))) def load_simbol_font(): self.btn_simbol_font.setText(load_font()) def load_message_font(): self.btn_message_font.setText(load_font()) #SIGNALS self.connect(self.btn_editor_font, SIGNAL("clicked()"), load_editor_font) #self.connect(self.btn_simbol_font, SIGNAL ("clicked()"), load_simbol_font) #self.connect(self.btn_message_font, SIGNAL("clicked()"), load_message_font) g_font = QGridLayout() g_font.addWidget(QLabel('Editor Font:'), 0, 0, Qt.AlignRight) #g_font.addWidget(QLabel('Simbol List:'),1, 0, Qt.AlignRight) #g_font.addWidget(QLabel('Messages Window:'),2,0,Qt.AlignRight) g_font.addWidget(self.btn_editor_font, 0, 1) #g_font.addWidget(self.btn_simbol_font, 1, 1) #g_font.addWidget(self.btn_message_font, 2, 1) self.gbox_fonts.setLayout(g_font) #Edition Tabs #Checks self.ch_showEditTabs = QCheckBox('Show Editor Tabs') self.ch_showEditTabs.setCheckState( self.settings.value('show_editor_tabs', 2).toInt()[0]) self.ch_showClose = QCheckBox('Show Close Button on Tabs') self.ch_showClose.setCheckState( self.settings.value('show_close_tabs', 2).toInt()[0]) self.ch_hidePanel = QCheckBox('F11 hide/show side Panels') self.ch_hidePanel.setCheckState( self.settings.value('hide_show_panels', 2).toInt()[0]) #Option self.opt_left = QRadioButton('Left') self.opt_right = QRadioButton('Right') if (self.settings.value('next_tabs_location', 1).toInt()[0] == 1): self.opt_right.setChecked(True) else: self.opt_left.setChecked(True) h_optionNewFiles = QHBoxLayout() h_optionNewFiles.addWidget(QLabel('Location for New Files Tabs')) h_optionNewFiles.addWidget(self.opt_left) h_optionNewFiles.addWidget(self.opt_right) v_tabs = QVBoxLayout() v_tabs.addWidget(self.ch_showEditTabs) v_tabs.addWidget(self.ch_showClose) v_tabs.addLayout(h_optionNewFiles) #v_tabs.addWidget(self.ch_hidePanel) self.gbox_tabs.setLayout(v_tabs) #Tabs Position #Buttons #self.btn_orientation_change = QPushButton self.btn_hchange = QPushButton(QIcon(resources.images['splitCRotate']), '') self.btn_hchange.setIconSize(QSize(64, 64)) self.btn_right_vchange = QPushButton( QIcon(resources.images['splitMRotate']), '') self.btn_right_vchange.setIconSize(QSize(64, 64)) #SIGNAL self.connect(self.btn_hchange, SIGNAL('clicked()'), parent._splitter_central_rotate) self.connect(self.btn_right_vchange, SIGNAL('clicked()'), parent._splitter_main_rotate) self.settings.endGroup() #End General Preferences self.settings.endGroup() g_tabPosition = QGridLayout() g_tabPosition.addWidget(self.btn_hchange, 0, 0) g_tabPosition.addWidget(self.btn_right_vchange, 0, 1) g_tabPosition.addWidget(QLabel('Vertical Change'), 1, 0, Qt.AlignCenter) g_tabPosition.addWidget(QLabel('Horizontal Change'), 1, 1, Qt.AlignCenter) self.gbox_tabsPosition.setLayout(g_tabPosition)
def initGui(self): # Setup menu self.quickosm_menu = QMenu('Quick OSM') self.quickosm_menu.setIcon(QIcon(':/plugins/QuickOSM/icon.png')) self.dock_menu = QMenu(tr('QuickOSM', u'Dock')) self.vector_menu = self.iface.vectorMenu() self.vector_menu.addMenu(self.quickosm_menu) # Main window self.mainWindowAction = QAction(QIcon(':/plugins/QuickOSM/icon.png'), u'QuickOSM', self.iface.mainWindow()) # noinspection PyUnresolvedReferences self.mainWindowAction.triggered.connect(self.openMainWindow) self.toolbar.addAction(self.mainWindowAction) self.iface.QuickOSM_mainWindowDialog = MainWindowDialog() # OSM File self.osmFileAction = QAction( QIcon(':/plugins/QuickOSM/resources/open.png'), tr('ui_osm_file', 'OSM File'), self.iface.mainWindow()) # noinspection PyUnresolvedReferences self.osmFileAction.triggered.connect(self.openOsmFileDockWidget) self.osmFileDockWidget = OsmFileDockWidget() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.osmFileDockWidget) self.osmFileDockWidget.hide() self.osmFileDockWidget.setObjectName('osmFileWidget') # My queries self.myQueriesAction = QAction( QIcon(':/plugins/QuickOSM/resources/favorites.png'), tr('ui_my_queries', 'My queries'), self.iface.mainWindow()) # noinspection PyUnresolvedReferences self.myQueriesAction.triggered.connect(self.openMyQueriesDockWidget) self.myQueriesDockWidget = MyQueriesDockWidget() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.myQueriesDockWidget) self.myQueriesDockWidget.hide() self.myQueriesDockWidget.setObjectName('myQueriesWidget') # Query self.queryAction = QAction( QIcon(':/plugins/QuickOSM/resources/edit.png'), tr('ui_query', 'Query'), self.iface.mainWindow()) # noinspection PyUnresolvedReferences self.queryAction.triggered.connect(self.openQueryDockWidget) self.queryDockWidget = QueryDockWidget() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.queryDockWidget) self.queryDockWidget.hide() self.queryDockWidget.setObjectName('queryWidget') # Quick query self.quickQueryAction = QAction( QIcon(':/plugins/QuickOSM/resources/quick.png'), tr('ui_quick_query', 'Quick query'), self.iface.mainWindow()) # noinspection PyUnresolvedReferences self.quickQueryAction.triggered.connect(self.openQuickQueryDockWidget) self.quickQueryDockWidget = QuickQueryDockWidget() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.quickQueryDockWidget) self.quickQueryDockWidget.hide() self.quickQueryDockWidget.setObjectName('quickQueryWidget') # Insert in the good order self.quickosm_menu.addAction(self.mainWindowAction) self.quickosm_menu.addMenu(self.dock_menu) self.dock_menu.addAction(self.quickQueryAction) self.dock_menu.addAction(self.queryAction) self.dock_menu.addAction(self.myQueriesAction) self.dock_menu.addAction(self.osmFileAction) # Connect signals and slots from dock self.queryDockWidget.signal_new_query_successful.connect( self.iface.QuickOSM_mainWindowDialog.refresh_my_queries_tree) self.queryDockWidget.signal_new_query_successful.connect( self.myQueriesDockWidget.refresh_my_queries_tree) self.myQueriesDockWidget.signal_delete_query_successful.connect( self.myQueriesDockWidget.refresh_my_queries_tree) self.myQueriesDockWidget.signal_delete_query_successful.connect( self.iface.QuickOSM_mainWindowDialog.refresh_my_queries_tree) # Connect signals and slots from mainWindow self.iface.QuickOSM_mainWindowDialog.signal_new_query_successful.\ connect(self.myQueriesDockWidget.refresh_my_queries_tree) self.iface.QuickOSM_mainWindowDialog.signal_new_query_successful.\ connect( self.iface.QuickOSM_mainWindowDialog.refresh_my_queries_tree) self.iface.QuickOSM_mainWindowDialog.signal_delete_query_successful.\ connect(self.myQueriesDockWidget.refresh_my_queries_tree) self.iface.QuickOSM_mainWindowDialog.signal_delete_query_successful.\ connect( self.iface.QuickOSM_mainWindowDialog.refresh_my_queries_tree) # Read the config file json_file_config = join(dirname(abspath(__file__)), 'config.json') if isfile(json_file_config): config_json = load(open(json_file_config)) for server in config_json['overpass_servers']: self.iface.QuickOSM_mainWindowDialog.comboBox_default_OAPI.\ addItem(server) # Check previous version and if new queries are available version = get_setting('version') current_version = get_current_version() if version != current_version: if new_queries_available(): message = 'New queries are available in the plugin. Would ' \ 'like to install them ? This will overwrite the ' \ 'current default queries.' title = 'QuickOSM' message = tr('QuickOSM', message) widget = self.iface.messageBar().createMessage(title, message) button_ok = QPushButton(widget) button_ok.setText(tr('QuickOSM', 'Install')) button_ok.pressed.connect(self.restoreDefaultQueries) widget.layout().addWidget(button_ok) self.iface.messageBar().pushWidget(widget, QgsMessageBar.INFO, 0) set_setting('version', current_version)
class AudioVideoTab(QWidget): def __init__(self, parent): super(AudioVideoTab, self).__init__(parent) self.parent = parent self.name = 'AudioVideo' self.defaultStr = self.tr('Default') self.DisableStream = self.tr('Disable') self.formats = config.video_formats frequency_values = [self.defaultStr] + config.video_frequency_values bitrate_values = [self.defaultStr] + config.video_bitrate_values rotation_options = [ self.tr('None'), '90 ' + self.tr('clockwise'), '90 ' + self.tr('clockwise') + ' + ' + self.tr('vertical flip'), '90 ' + self.tr('counter clockwise'), '90 ' + self.tr('counter clockwise') + ' + ' + self.tr('vertical flip'), '180', self.tr('horizontal flip'), self.tr('vertical flip') ] digits_validator = QRegExpValidator(QRegExp(r'[1-9]\d*'), self) digits_validator_wzero = QRegExpValidator(QRegExp(r'\d*'), self) digits_validator_minus = QRegExpValidator(QRegExp(r'(-1|[1-9]\d*)'), self) time_validator = QRegExpValidator( QRegExp(r'\d{1,2}:\d{1,2}:\d{1,2}\.\d+'), self) converttoQL = QLabel(self.tr('Convert to:')) self.extQCB = QComboBox() self.extQCB.setMinimumWidth(100) vidcodecQL = QLabel('Video codec:') self.vidcodecQCB = QComboBox() self.vidcodecQCB.setMinimumWidth(110) audcodecQL = QLabel('Audio codec:') self.audcodecQCB = QComboBox() self.audcodecQCB.setMinimumWidth(110) hlayout1 = utils.add_to_layout('h', converttoQL, self.extQCB, QSpacerItem(180, 20), vidcodecQL, self.vidcodecQCB, audcodecQL, self.audcodecQCB) commandQL = QLabel(self.tr('Command:')) self.commandQLE = QLineEdit() self.presetQPB = QPushButton(self.tr('Preset')) self.defaultQPB = QPushButton(self.defaultStr) hlayout2 = utils.add_to_layout('h', commandQL, self.commandQLE, self.presetQPB, self.defaultQPB) sizeQL = QLabel(self.tr('Video Size:')) aspectQL = QLabel(self.tr('Aspect:')) frameQL = QLabel(self.tr('Frame Rate (fps):')) bitrateQL = QLabel(self.tr('Video Bitrate (kbps):')) self.widthQLE = utils.create_LineEdit((70, 16777215), digits_validator_minus, 4) self.heightQLE = utils.create_LineEdit((70, 16777215), digits_validator_minus, 4) label = QLabel('<html><p align="center">x</p></html>') layout1 = utils.add_to_layout('h', self.widthQLE, label, self.heightQLE) self.aspect1QLE = utils.create_LineEdit((50, 16777215), digits_validator, 2) self.aspect2QLE = utils.create_LineEdit((50, 16777215), digits_validator, 2) label = QLabel('<html><p align="center">:</p></html>') layout2 = utils.add_to_layout('h', self.aspect1QLE, label, self.aspect2QLE) self.frameQLE = utils.create_LineEdit((120, 16777215), digits_validator, 4) self.bitrateQLE = utils.create_LineEdit((130, 16777215), digits_validator, 6) labels = [sizeQL, aspectQL, frameQL, bitrateQL] widgets = [layout1, layout2, self.frameQLE, self.bitrateQLE] self.preserveaspectQChB = QCheckBox(self.tr("Preserve aspect ratio")) self.preservesizeQChB = QCheckBox(self.tr("Preserve video size")) preserve_layout = utils.add_to_layout('v', self.preserveaspectQChB, self.preservesizeQChB) videosettings_layout = QHBoxLayout() for a, b in zip(labels, widgets): a.setText('<html><p align="center">{0}</p></html>'.format( a.text())) layout = utils.add_to_layout('v', a, b) videosettings_layout.addLayout(layout) if a == aspectQL: # add vidaspectCB in layout after aspectQL videosettings_layout.addLayout(preserve_layout) freqQL = QLabel(self.tr('Frequency (Hz):')) chanQL = QLabel(self.tr('Audio Channels:')) bitrateQL = QLabel(self.tr('Audio Bitrate (kbps):')) threadsQL = QLabel(self.tr('Threads:')) self.freqQCB = QComboBox() self.freqQCB.addItems(frequency_values) self.chan1QRB = QRadioButton('1') self.chan1QRB.setMaximumSize(QSize(51, 16777215)) self.chan2QRB = QRadioButton('2') self.chan2QRB.setMaximumSize(QSize(51, 16777215)) self.group = QButtonGroup() self.group.addButton(self.chan1QRB) self.group.addButton(self.chan2QRB) spcr1 = QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Minimum) spcr2 = QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Minimum) chanlayout = utils.add_to_layout('h', spcr1, self.chan1QRB, self.chan2QRB, spcr2) self.audbitrateQCB = QComboBox() self.audbitrateQCB.addItems(bitrate_values) self.threadsQLE = utils.create_LineEdit((50, 16777215), digits_validator_wzero, 1) labels = [freqQL, bitrateQL, chanQL, threadsQL] widgets = [ self.freqQCB, self.audbitrateQCB, chanlayout, self.threadsQLE ] audiosettings_layout = QHBoxLayout() for a, b in zip(labels, widgets): a.setText('<html><p align="center">{0}</p></html>'.format( a.text())) layout = utils.add_to_layout('v', a, b) audiosettings_layout.addLayout(layout) time_format = " (hh:mm:ss):" beginQL = QLabel(self.tr("Split file. Begin time") + time_format) self.beginQLE = utils.create_LineEdit(None, time_validator, None) durationQL = QLabel(self.tr("Duration") + time_format) self.durationQLE = utils.create_LineEdit(None, time_validator, None) hlayout4 = utils.add_to_layout('h', beginQL, self.beginQLE, durationQL, self.durationQLE) embedQL = QLabel(self.tr("Embed subtitle:")) self.embedQLE = QLineEdit() self.embedQTB = QToolButton() self.embedQTB.setText("...") rotateQL = QLabel(self.tr("Rotate:")) self.rotateQCB = QComboBox() self.rotateQCB.addItems(rotation_options) hlayout5 = utils.add_to_layout('h', rotateQL, self.rotateQCB, embedQL, self.embedQLE, self.embedQTB) hidden_layout = utils.add_to_layout('v', videosettings_layout, audiosettings_layout, hlayout4, hlayout5) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.moreQPB = QPushButton(QApplication.translate('Tab', 'More')) self.moreQPB.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.moreQPB.setCheckable(True) hlayout3 = utils.add_to_layout('h', line, self.moreQPB) self.frame = QFrame() self.frame.setLayout(hidden_layout) self.frame.hide() final_layout = utils.add_to_layout('v', hlayout1, hlayout2, hlayout3, self.frame) self.setLayout(final_layout) self.presetQPB.clicked.connect(self.choose_preset) self.defaultQPB.clicked.connect(self.set_default_command) self.embedQTB.clicked.connect(self.open_subtitle_file) self.moreQPB.toggled.connect(self.frame.setVisible) self.moreQPB.toggled.connect( lambda: QTimer.singleShot(100, self.resize_parent)) self.widthQLE.textChanged.connect(self.command_update_size) self.heightQLE.textChanged.connect(self.command_update_size) self.aspect1QLE.textChanged.connect(self.command_update_aspect) self.aspect2QLE.textChanged.connect(self.command_update_aspect) self.frameQLE.textChanged.connect(self.command_update_frames) self.bitrateQLE.textChanged.connect(self.command_update_vidbitrate) self.threadsQLE.textChanged.connect(self.command_update_threads) self.beginQLE.textChanged.connect(self.command_update_begin_time) self.durationQLE.textChanged.connect(self.command_update_duration) self.embedQLE.textChanged.connect(self.command_update_subtitles) self.vidcodecQCB.currentIndexChanged.connect( self.command_update_vcodec) self.audcodecQCB.currentIndexChanged.connect( self.command_update_acodec) self.freqQCB.currentIndexChanged.connect(self.command_update_frequency) self.rotateQCB.currentIndexChanged.connect( self.command_update_rotation) self.audbitrateQCB.currentIndexChanged.connect( self.command_update_audbitrate) self.chan1QRB.clicked.connect( lambda: self.command_update_channels('1')) self.chan2QRB.clicked.connect( lambda: self.command_update_channels('2')) self.preserveaspectQChB.toggled.connect( self.command_update_preserve_aspect) self.preservesizeQChB.toggled.connect( self.command_update_preserve_size) def resize_parent(self): """Give MainWindow its default size.""" self.parent.setMinimumSize(self.parent.sizeHint()) self.parent.resize(self.parent.sizeHint()) def clear(self): """Clear all values of graphical widgets.""" lines = [ self.commandQLE, self.widthQLE, self.heightQLE, self.aspect1QLE, self.aspect2QLE, self.frameQLE, self.bitrateQLE, self.threadsQLE, self.beginQLE, self.embedQLE, self.durationQLE ] for i in lines: i.clear() self.vidcodecQCB.setCurrentIndex(0) self.audcodecQCB.setCurrentIndex(0) self.freqQCB.setCurrentIndex(0) self.audbitrateQCB.setCurrentIndex(0) self.rotateQCB.setCurrentIndex(0) self.preserveaspectQChB.setChecked(False) self.preservesizeQChB.setChecked(False) self.group.setExclusive(False) self.chan1QRB.setChecked(False) self.chan2QRB.setChecked(False) self.group.setExclusive(True) # setExclusive(False) in order to be able to uncheck checkboxes and # then setExclusive(True) so only one radio button can be set def fill_video_comboboxes(self, vcodecs, acodecs, extraformats): vcodecs = [i for i in vcodecs.split("\n")] if vcodecs else [] acodecs = [i for i in acodecs.split("\n")] if acodecs else [] extraformats = [i for i in extraformats.split("\n") ] if extraformats else [] self.vidcodecQCB.currentIndexChanged.disconnect() self.audcodecQCB.currentIndexChanged.disconnect() self.vidcodecQCB.clear() self.audcodecQCB.clear() self.extQCB.clear() self.vidcodecQCB.addItems([self.defaultStr, self.DisableStream] + vcodecs) self.audcodecQCB.addItems([self.defaultStr, self.DisableStream] + acodecs) self.extQCB.addItems(sorted(self.formats + extraformats)) self.vidcodecQCB.currentIndexChanged.connect( self.command_update_vcodec) self.audcodecQCB.currentIndexChanged.connect( self.command_update_acodec) def ok_to_continue(self): """ Check if everything is ok with audiovideotab to continue conversion. Check if: - Either ffmpeg or avconv are installed. Return True if all tests pass, else False. """ if self.parent.vidconverter is None: QMessageBox.warning( self, 'FF Multi Converter - ' + self.tr('Error!'), self. tr('Neither ffmpeg nor libav are installed.' '\nYou will not be able to convert audio/video files until you' ' install one of them.')) return False return True def open_subtitle_file(self): """ Get the filename using standard QtDialog and update embedQLE's text. """ fname = QFileDialog.getOpenFileName( self, 'FF Multi Converter - ' + self.tr('Choose File'), config.home, 'Subtitles (*.srt *.sub *.ssa *.ass)') if fname: self.embedQLE.setText(fname) def set_default_command(self): """Set the default value to self.commandQLE.""" self.clear() self.commandQLE.setText(self.parent.default_command) def choose_preset(self): """ Open the presets dialog and update self.commandQLE, and self.extQCB and with the appropriate values. """ dialog = presets_dlgs.ShowPresets(choose=True) if dialog.exec_() and dialog.the_command is not None: self.clear() self.commandQLE.setText(dialog.the_command) self.commandQLE.home(False) find = self.extQCB.findText(dialog.the_extension) if find >= 0: self.extQCB.setCurrentIndex(find) def command_update_size(self): command = self.commandQLE.text() text1 = self.widthQLE.text() text2 = self.heightQLE.text() if not (text1 == '-1' or text2 == '-1'): self.preserveaspectQChB.setChecked(False) if (text1 or text2) and not (text1 and text2) or (text1 == '-' or text2 == '-'): return regex = r'(\s+|^)-s(:v){0,1}\s+\d+x\d+(\s+|$)' if re.search(regex, command): command = re.sub(regex, '', command) regex = r'(,*\s*){0,1}(scale=-?\d+:-?\d+)(\s*,*\s*){0,1}' _filter = "scale={0}:{1}".format(text1, text2) if text1 and text2 else '' self.commandQLE.setText( utils.update_cmdline_text(command, _filter, regex, bool(text1 and text2), 0, 2)) def command_update_preserve_size(self): checked = self.preservesizeQChB.isChecked() self.widthQLE.setEnabled(not checked) self.heightQLE.setEnabled(not checked) if checked: self.widthQLE.clear() self.heightQLE.clear() # command_update_size() is triggered here command = self.commandQLE.text() regex = r'(\s+|^)-s\s+\d+x\d+(\s+|$)' command = re.sub(' +', ' ', re.sub(regex, ' ', command)).strip() self.commandQLE.setText(command) def command_update_aspect(self): command = self.commandQLE.text() text1 = self.aspect1QLE.text() text2 = self.aspect2QLE.text() if (text1 or text2) and not (text1 and text2): return regex = r'(\s+|^)-aspect\s+\d+:\d+(\s+|$)' s = ' -aspect {0}:{1} '.format(text1, text2) if text1 and text2 else ' ' if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(' +', ' ', command).strip() self.commandQLE.setText(command) def command_update_preserve_aspect(self): command = self.commandQLE.text() checked = self.preserveaspectQChB.isChecked() self.aspect1QLE.setEnabled(not checked) self.aspect2QLE.setEnabled(not checked) if checked: self.aspect1QLE.clear() self.aspect2QLE.clear() # self.command_update_aspect() is triggered here regex = r'(,*\s*){0,1}(scale=(-?\d+):(-?\d+))(\s*,*\s*){0,1}' search = re.search(regex, command) if search: width = search.groups()[2] height = search.groups()[3] if not (width == '-1' or height == '-1'): s = "scale=-1:{0}".format(height) command = re.sub(regex, r'\1{0}\5'.format(s), command) self.widthQLE.setText('-1') self.heightQLE.setText(height) regex = r'(\s+|^)-aspect\s+\d+:\d+(\s+|$)' command = re.sub(' +', ' ', re.sub(regex, ' ', command)).strip() self.commandQLE.setText(command) def command_update_frames(self): command = self.commandQLE.text() text = self.frameQLE.text() regex = r'(\s+|^)-r\s+\d+(\s+|$)' s = ' -r {0} '.format(text) if text else ' ' if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(' +', ' ', command).strip() self.commandQLE.setText(command) def command_update_vidbitrate(self): command = self.commandQLE.text() text = self.bitrateQLE.text() regex = r'(\s+|^)-b(:v){0,1}\s+\d+[kKmM](\s+|$)' s = ' -b:v {0}k '.format(text) if text else ' ' if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub('-sameq', '', command) command = re.sub(' +', ' ', command).strip() self.commandQLE.setText(command) def command_update_frequency(self): command = self.commandQLE.text() text = self.freqQCB.currentText() regex = r'(\s+|^)-ar\s+\d+(\s+|$)' s = ' -ar {0} '.format( text) if self.freqQCB.currentIndex() != 0 else ' ' if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(' +', ' ', command).strip() self.commandQLE.setText(command) def command_update_audbitrate(self): command = self.commandQLE.text() text = self.audbitrateQCB.currentText() regex = r'(\s+|^)-(ab|b:a)\s+\d+[kKmM](\s+|$)' if self.audbitrateQCB.currentIndex() != 0: s = ' -b:a {0}k '.format(text) else: s = ' ' if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(' +', ' ', command).strip() self.commandQLE.setText(command) def command_update_channels(self, channel): command = self.commandQLE.text() regex = r'(\s+|^)-ac\s+\d+(\s+|$)' s = ' -ac {0} '.format(channel) if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(' +', ' ', command).strip() self.commandQLE.setText(command) def command_update_threads(self): command = self.commandQLE.text() text = self.threadsQLE.text() regex = r'(\s+|^)-threads\s+\d+(\s+|$)' s = ' -threads {0} '.format(text) if text else ' ' if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(' +', ' ', command).strip() self.commandQLE.setText(command) def command_update_begin_time(self): command = self.commandQLE.text() text = self.beginQLE.text() regex = r'(\s+|^)-ss\s+\S+(\s+|$)' s = ' -ss {0} '.format(text) if text else ' ' if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(' +', ' ', command).strip() self.commandQLE.setText(command) def command_update_duration(self): command = self.commandQLE.text() text = self.durationQLE.text() regex = r'(\s+|^)-t\s+\S+(\s+|$)' s = ' -t {0} '.format(text) if text else ' ' if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(' +', ' ', command).strip() self.commandQLE.setText(command) def command_update_vcodec(self): command = self.commandQLE.text() text = self.vidcodecQCB.currentText() regex = r'(\s+|^)-(vcodec|c:v)\s+\S+(\s+|$)' regex_vn = r'(\s+|^)-vn(\s+|$)' if self.vidcodecQCB.currentIndex() == 1: s = ' -vn '.format(text) elif self.vidcodecQCB.currentIndex() == 0: s = ' ' else: s = ' -vcodec {0} '.format(text) if re.search(regex, command): command = re.sub(regex, s, command) elif re.search(regex_vn, command): command = re.sub(regex_vn, s, command) else: command += s command = re.sub(' +', ' ', command).strip() self.commandQLE.setText(command) def command_update_acodec(self): command = self.commandQLE.text() text = self.audcodecQCB.currentText() regex = r'(\s+|^)-(acodec|c:a)\s+\S+(\s+|$)' regex_an = r'(\s+|^)-an(\s+|$)' if self.audcodecQCB.currentIndex() == 1: s = ' -an '.format(text) elif self.audcodecQCB.currentIndex() == 0: s = ' ' else: s = ' -acodec {0} '.format(text) if re.search(regex, command): command = re.sub(regex, s, command) elif re.search(regex_an, command): command = re.sub(regex_an, s, command) else: command += s command = re.sub(' +', ' ', command).strip() self.commandQLE.setText(command) def command_update_subtitles(self): command = self.commandQLE.text() regex = r'(,*\s*){0,1}(subtitles=\'.*\')(\s*,*\s*){0,1}' text = self.embedQLE.text() _filter = "subtitles='{0}'".format(text) if text else '' self.commandQLE.setText( utils.update_cmdline_text(command, _filter, regex, bool(text), 0, 2)) def command_update_rotation(self): command = self.commandQLE.text() regex = r'(,*\s*){0,1}(transpose=\d(,\s*transpose=\d)*|vflip|hflip)(\s*,*\s*){0,1}' rotate = self.rotateQCB.currentIndex() if rotate == 0: # none _filter = '' elif rotate == 1: # 90 clockwise _filter = 'transpose=1' elif rotate == 2: # 90 clockwise + vertical flip _filter = 'transpose=3' elif rotate == 3: # 90 counter clockwise _filter = 'transpose=2' elif rotate == 4: # 90 counter clockwise + vertical flip _filter = 'transpose=0' elif rotate == 5: # 180 _filter = 'transpose=2,transpose=2' elif rotate == 6: # horizontal flip _filter = 'hflip' elif rotate == 7: # vertical flip _filter = 'vflip' self.commandQLE.setText( utils.update_cmdline_text(command, _filter, regex, bool(rotate != 0), 0, 3))
class MainWindow(QMainWindow, Ui_MainWindow): '''Main application window''' selectedEdgeChanged = pyqtSignal(object) selectedEdgeChangedList = pyqtSignal(object) #when edge selected in QListWidget unitCellChanged = pyqtSignal() latticeVisibleChanged = pyqtSignal(object) # used to bind with mpl.event arrowsVisibleChanged = pyqtSignal(object) # used to bind with mpl.event def __init__(self, fileName=None, TEXT_MODE=True): super(MainWindow, self).__init__() self.setupUi(self) self.prefFileName = os.path.dirname(__file__)+'/../resources/preferences.xml' self.SETTINGS = ET.parse(self.prefFileName).getroot() self.CURRENT_THEME = DealXML.get_child_by_name(self.SETTINGS,"THEME","Current theme") self.TEXT_MODE = TEXT_MODE self.size = (2,2,2) self.spinBox_sizeL.setValue(self.size[0]) self.spinBox_sizeW.setValue(self.size[1]) self.spinBox_sizeH.setValue(self.size[2]) self.spinBox_type.clear() self.radioButton_output.setChecked(TEXT_MODE) self.setup_mpl_canvas() # initialize canvas path = self.prefFileName if fileName is None else fileName self.importXML_fromFile(path) self.fileNameXML = fileName self.label_fileNameXML.setText("XML library file: " + self.getFileLabelText()) self.msb_noActiveEdge = QMessageBox() self.msb_noActiveEdge.setIcon(QMessageBox.Critical) self.msb_noActiveEdge.setWindowTitle("Message") self.msb_noActiveEdge.setStandardButtons(QMessageBox.Ok) self.msb_noActiveEdge.setText("No edge is selected") # setup signals and slots self.btnEditXML.clicked.connect(self.editXML_callback) self.spinBox_sizeL.valueChanged.connect(self.changeSize_callback) self.spinBox_sizeW.valueChanged.connect(self.changeSize_callback) self.spinBox_sizeH.valueChanged.connect(self.changeSize_callback) self.btnDel.clicked.connect(self.delteEdge_callback) self.btnClear.clicked.connect(self.gee.clearEdges_callback) self.btnChangeType.clicked.connect(self.changeType_callback) self.btnLength.clicked.connect(self.addDistEdges_callback) self.listEdges.currentItemChanged.connect(self.selectEdgeList_callback) self.radioButton_output.toggled.connect(self.change_textMode) self.selectedEdgeChanged.connect(self.selectEdgeSignal_slot) self.unitCellChanged.connect(self.update_listEdges) self.setup_menu() if self.TEXT_MODE: print(self.gee.__doc__) def setup_menu(self): '''setup slot for menu actions''' # configure menuFile self.action_ImportXML.triggered.connect(self.importXMLdlg_callback) self.action_ImportCryst.triggered.connect(self.importCryst_callback) self.action_SaveXML.triggered.connect(self.saveXML_callback) self.action_SaveXML_as.triggered.connect(self.saveXML_as_callback) self.action_ExportIMG.triggered.connect(self.exportIMG_callback) self.action_ExportAnim.triggered.connect(self.exportAnim_callback) self.action_Quit.triggered.connect(self.quit_callback) # configure menuEdit self.action_EditXML.triggered.connect(self.editXML_callback) self.action_AddSimEdges.triggered.connect(self.addSimEdges_callback) self.action_AddDistEdges.triggered.connect(self.addDistEdges_callback) self.action_ChangeType.triggered.connect(self.menuChangeType_callback) self.action_DelEdge.triggered.connect(self.delteEdge_callback) self.action_ClearEdges.triggered.connect(self.gee.clearEdges_callback) self.action_Pref.triggered.connect(self.preferences_callback) # configure menuHelo self.action_About.triggered.connect(self.about_callback) self.action_Doc.triggered.connect(self.doc_callback) def setup_mpl_canvas(self): ''' setup matplotlib manipulation pane widget for displaying and editing lattice graph ''' self.dpi = 100 self.fig = Figure((5.0, 5.0), dpi=self.dpi) self.canvas = FigureCanvas(self.fig) self.ax = self.fig.gca(projection='3d') self.fig.subplots_adjust(left=0, bottom=0, right=1, top=1) self.canvas.setParent(self.mplWidget) self.mplLayout.addWidget(self.canvas) self.canvas.setFocusPolicy(Qt.ClickFocus) self.canvas.setFocus() # add aniation button self.btnPlay = QPushButton("Animate") self.btnPlay.setStatusTip("Open animation manager.") self.btnPlay.clicked.connect(self.exportAnim_callback) self.btnPlay.setFocusPolicy(Qt.NoFocus) mplHbox = QHBoxLayout() mplHbox.addWidget(self.btnPlay) mplHbox.addStretch() mplVbox = QVBoxLayout() mplVbox.addLayout(mplHbox) mplVbox.addStretch() self.canvas.setLayout(mplVbox) def importXML_fromFile(self, path): '''import lattice graph form xml file''' self.fileNameXML = path self.parser = ParseXML(fileName = self.fileNameXML) LG_name_list = self.parser.get_LATTICEGRAPH_names() if len(LG_name_list) > 1: self.dlgSelectLG = DialogSelectLG(self, LG_name_list) self.dlgSelectLG.show() else: self.importXml(LG_name_list[0]) def importXml(self, LG_name): '''import lattice graph with given name from predefined parser - ParseXML object''' self.LATTICEGRAPH_name = LG_name self.label_fileNameXML.setText("XML library file: "+self.getFileLabelText()) self.label_LG_name.setText("Lattice graph name: "+self.LATTICEGRAPH_name) if self.parser is None: raise ValueError("Parser is not defined") self.lattice, self.UC = self.parser.parse_LATTICEGRAPH(self.LATTICEGRAPH_name) self.cluster = CrystalCluster(self.UC, self.lattice, self.size) self.ax.clear() self.gee = GraphEdgesEditor(self.ax, self.cluster, parent=self, display_report=True) self.canvas.draw() self.update_listEdges() self.unitCellChanged.emit() def update_listEdges(self): '''is used to update QListWidget when unit cell is changed''' self.initialization = True # block QListWidget valuechanged callback self.listEdges.clear() defaultListItem = QListWidgetItem('') self.listEdges_idToItem = {None: defaultListItem} self.listEdges_ItemToId = {defaultListItem.text(): None} for key, edge in self.gee.UC.edges.items(): newItem = QListWidgetItem(str(edge)) self.listEdges.addItem(newItem) self.listEdges_idToItem[key] = newItem self.listEdges_ItemToId[newItem.text()] = key self.listEdges.addItem(defaultListItem) self.listEdges.setCurrentItem(defaultListItem) self.initialization = False # relieze QListWidget valuechanged callback def changeSize_callback(self): '''called when cluter size in spinBox is chanaged''' self.size = (self.spinBox_sizeL.value(), self.spinBox_sizeW.value(), self.spinBox_sizeH.value()) self.gee.reset_size(self.size) def changeType_callback(self): '''called when value of self.spinBox_type is changed''' if self.gee.e_active_ind is None: self.msb_noActiveEdge.exec_() else: self.gee.change_active_edge_type(self.spinBox_type.value()) def selectEdgeList_callback(self, selectedItem): '''called when edge is selected in QListWidget''' if not self.initialization: activeEdge_id = self.listEdges_ItemToId[selectedItem.text()] self.gee.select_edge(activeEdge_id) self.selectedEdgeChangedList.emit(activeEdge_id) if activeEdge_id is None: msg = " active edge unselected" self.spinBox_type.clear() else: msg = " selected edge: {}".format(self.cluster.UC.edges[activeEdge_id]) _type = self.cluster.UC.edges[activeEdge_id].type self.spinBox_type.setValue(_type) self.statusBar().showMessage(msg, 2000) if self.TEXT_MODE: print(msg) def selectEdgeSignal_slot(self, activeEdge_id): '''Process selecting edge signal''' activeItem = self.listEdges_idToItem[activeEdge_id] self.listEdges.setCurrentItem(activeItem) def change_textMode(self, _bool): '''turn on/off printing actions into terminal''' self.TEXT_MODE = _bool self.gee.display_report = _bool msg = " displaying actions in terminal is turned {}".format("on" if _bool else "off") self.statusBar().showMessage(msg, 2000) print(msg) def getFileLabelText(self): '''Returns the label string of the xml library file''' if self.fileNameXML is None: return "None" else: fileName = os.path.basename(self.fileNameXML) dirName = os.path.basename(os.path.dirname(self.fileNameXML)) return os.path.join("...", dirName, fileName) def importXMLdlg_callback(self): '''when import acttion is activated''' output = QFileDialog.getOpenFileName(self, 'Open xml library containing Lattice Graph', filter = "XML files (*.xml);;All files (*.*)") path = getPathString(output) if path != "": self.importXML_fromFile(path) def importCryst_callback(self): '''import crystal providing lattice and unit cell parameters''' self.dlgImportCryst = DialogImportCryst(self) self.dlgImportCryst.show() def saveXML_callback(self): '''save changes to lattice graph xml library file''' if self.fileNameXML == None: self.saveXML_as_callback() else: self.exporter = ExportXML(self.gee.cluster.lattice, self.gee.cluster.UC, self.LATTICEGRAPH_name) self.exporter.export_to_lib(self.fileNameXML) def saveXML_as_callback(self): '''save lattice graph to xml library file''' dialog = DialogExportLG(self, self.LATTICEGRAPH_name, self.cluster.lattice.atrib["BOUNDARY"]) if dialog.exec_(): self.LATTICEGRAPH_name = str(dialog.lineEdit_LGname.text()) self.gee.cluster.lattice.atrib["BOUNDARY"]= \ str(dialog.comboBox_boundary.currentText()) output = QFileDialog.getSaveFileName(self, filter="XML files (*.xml)") path = getPathString(output) # if not canceled if path != '': self.fileNameXML = path self.exporter = ExportXML(self.gee.cluster.lattice, self.gee.cluster.UC, self.LATTICEGRAPH_name) self.exporter.export_to_lib(self.fileNameXML) self.label_fileNameXML.setText("XML library file: "+self.getFileLabelText()) def exportIMG_callback(self): '''Savve image of the Heisenberg model (lattice graph)''' output = QFileDialog.getSaveFileName(self,caption='Save model image', filter="Images (*.png *.xpm *.jpg);;All files (*.*)") path = getPathString(output) if path != '': self.exportIMG(path) def exportIMG(self, path): '''Savve image of the Heisenberg model (lattice graph)''' self.canvas.print_figure(path, dpi=self.dpi, bbox_inches='tight', pad_inches=0) self.statusBar().showMessage('Saved to %s' % path, 2000) def exportAnim_callback(self): '''animate lattice graph mpl_pane and open animation manager''' self.dlgExportAnim = QDialogAnimManager(self.ax) self.dlgExportAnim.show() # disable animated GraphEdgeEditor artists self.gee.sc_active.set_visible(False) self.gee.new_edge.set_visible(False) # enabele animated GraphEdgeEditor artists self.dlgExportAnim.closed.connect(self.gee.sc_active.set_visible) self.dlgExportAnim.closed.connect(self.gee.new_edge.set_visible) def quit_callback(self): self.close() def editXML_callback(self): ''' open lattice graph xml code editor''' self.dlgEditXML = DialogEditXML(self) self.dlgEditXML.show() if self.TEXT_MODE: print(" open lattice graph xml code editor") def addSimEdges_callback(self): '''search for and add edges that have the same length as selected one''' if self.gee.e_active_ind is None: self.msb_noActiveEdge.exec_() else: self.gee.searchActiveDistEdge_callback() def addDistEdges_callback(self): '''opens edge length manipulation manager''' self.gee.select_edge(None) self.selectEdgeSignal_slot(None) self.dlgDistSearch = DialogDistSearch(self) self.dlgDistSearch.show() def menuChangeType_callback(self): '''change selected edge type''' if self.gee.e_active_ind is None: self.msb_noActiveEdge.exec_() else: self.dlg = DialogChangeEdgeType(self) self.dlg.show() def delteEdge_callback(self): '''delete selected edge''' if self.gee.e_active_ind is None: self.msb_noActiveEdge.exec_() else: self.gee.delete_active_edge_callback() def preferences_callback(self): '''Calls preference dialog''' self.dlgPref = MyDialogPreferences(parent = self) self.dlgPref.applySignal.connect(self.applyPref_callback) self.arrowsVisibleChanged.connect(self.dlgPref.prefWidget.checkBox_arrows.setChecked) self.latticeVisibleChanged.connect(self.dlgPref.prefWidget.checkBox_lattice.setChecked) self.dlgPref.show() def applyPref_callback(self): '''when apply button is cklicked in DialogPreferences''' self.gee.initialize_theme(self.CURRENT_THEME) self.gee.set_artists_properties() def about_callback(self): '''display app help''' self.msg = QMessageBox() self.msg.setIcon(QMessageBox.Information) self.msg.setTextFormat(Qt.RichText) text = ''' <b>Lattice graph designer 1.0a1</b> <br> Copyright © 2017, Ivan Luchko and Project Contributors <br> Licensed under the terms of the MIT License <br><br> Lattice graph designer is a tool which allows to visualize and create a lattice graph model using the intuitive GUI and interactive 3D drag-and-drop graph manipulation pane. <br><br> It was primarily created for the <a href="http://alps.comp-phys.org">ALPS project</a> to deal with a lattice graph of the <a href="https://en.wikipedia.org/wiki/Heisenberg_model_(quantum)">Heisenberg model</a> defined in <a href="http://alps.comp-phys.org/mediawiki/index.php/Tutorials:LatticeHOWTO"> ALPS xml graph format</a>. <br><br> Support of the other formats and projects can be extended. <br><br> For bug reports and feature requests, please go to our <a href="https://github.com/luchko/latticegraph_designer">Github website</a>. ''' self.msg.setText(text) self.msg.setWindowTitle("About Lattice graph designer") self.msg.setStandardButtons(QMessageBox.Ok) self.msg.exec_() def doc_callback(self): '''open documentation''' webbrowser.open_new_tab("https://latticegraph-designer.readthedocs.io")
def __init__(self, parent, text, title=None, icon=None, contents_title=None, varname=None): QDialog.__init__(self, parent) # Destroying the C++ object right after closing the dialog box, # otherwise it may be garbage-collected in another QThread # (e.g. the editor's analysis thread in Spyder), thus leading to # a segmentation fault on UNIX or an application crash on Windows self.setAttribute(Qt.WA_DeleteOnClose) if title is None: title = _("Import wizard") self.setWindowTitle(title) if icon is None: self.setWindowIcon(get_icon("fileimport.png")) if contents_title is None: contents_title = _("Raw text") if varname is None: varname = _("variable_name") self.var_name, self.clip_data = None, None # Setting GUI self.tab_widget = QTabWidget(self) self.text_widget = ContentsWidget(self, text) self.table_widget = PreviewWidget(self) self.tab_widget.addTab(self.text_widget, _("text")) self.tab_widget.setTabText(0, contents_title) self.tab_widget.addTab(self.table_widget, _("table")) self.tab_widget.setTabText(1, _("Preview")) self.tab_widget.setTabEnabled(1, False) name_layout = QHBoxLayout() name_h_spacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) name_layout.addItem(name_h_spacer) name_label = QLabel(_("Name")) name_layout.addWidget(name_label) self.name_edt = QLineEdit() self.name_edt.setMaximumWidth(100) self.name_edt.setText(varname) name_layout.addWidget(self.name_edt) btns_layout = QHBoxLayout() cancel_btn = QPushButton(_("Cancel")) btns_layout.addWidget(cancel_btn) self.connect(cancel_btn, SIGNAL("clicked()"), self, SLOT("reject()")) h_spacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) btns_layout.addItem(h_spacer) self.back_btn = QPushButton(_("Previous")) self.back_btn.setEnabled(False) btns_layout.addWidget(self.back_btn) self.connect(self.back_btn, SIGNAL("clicked()"), ft_partial(self._set_step, step=-1)) self.fwd_btn = QPushButton(_("Next")) btns_layout.addWidget(self.fwd_btn) self.connect(self.fwd_btn, SIGNAL("clicked()"), ft_partial(self._set_step, step=1)) self.done_btn = QPushButton(_("Done")) self.done_btn.setEnabled(False) btns_layout.addWidget(self.done_btn) self.connect(self.done_btn, SIGNAL("clicked()"), self, SLOT("process()")) self.connect(self.text_widget, SIGNAL("asDataChanged(bool)"), self.fwd_btn, SLOT("setEnabled(bool)")) self.connect(self.text_widget, SIGNAL("asDataChanged(bool)"), self.done_btn, SLOT("setDisabled(bool)")) layout = QVBoxLayout() layout.addLayout(name_layout) layout.addWidget(self.tab_widget) layout.addLayout(btns_layout) self.setLayout(layout)
def __init__(self, parent): super(AudioVideoTab, self).__init__(parent) self.parent = parent self.name = 'AudioVideo' self.defaultStr = self.tr('Default') self.DisableStream = self.tr('Disable') self.formats = config.video_formats frequency_values = [self.defaultStr] + config.video_frequency_values bitrate_values = [self.defaultStr] + config.video_bitrate_values rotation_options = [ self.tr('None'), '90 ' + self.tr('clockwise'), '90 ' + self.tr('clockwise') + ' + ' + self.tr('vertical flip'), '90 ' + self.tr('counter clockwise'), '90 ' + self.tr('counter clockwise') + ' + ' + self.tr('vertical flip'), '180', self.tr('horizontal flip'), self.tr('vertical flip') ] digits_validator = QRegExpValidator(QRegExp(r'[1-9]\d*'), self) digits_validator_wzero = QRegExpValidator(QRegExp(r'\d*'), self) digits_validator_minus = QRegExpValidator(QRegExp(r'(-1|[1-9]\d*)'), self) time_validator = QRegExpValidator( QRegExp(r'\d{1,2}:\d{1,2}:\d{1,2}\.\d+'), self) converttoQL = QLabel(self.tr('Convert to:')) self.extQCB = QComboBox() self.extQCB.setMinimumWidth(100) vidcodecQL = QLabel('Video codec:') self.vidcodecQCB = QComboBox() self.vidcodecQCB.setMinimumWidth(110) audcodecQL = QLabel('Audio codec:') self.audcodecQCB = QComboBox() self.audcodecQCB.setMinimumWidth(110) hlayout1 = utils.add_to_layout('h', converttoQL, self.extQCB, QSpacerItem(180, 20), vidcodecQL, self.vidcodecQCB, audcodecQL, self.audcodecQCB) commandQL = QLabel(self.tr('Command:')) self.commandQLE = QLineEdit() self.presetQPB = QPushButton(self.tr('Preset')) self.defaultQPB = QPushButton(self.defaultStr) hlayout2 = utils.add_to_layout('h', commandQL, self.commandQLE, self.presetQPB, self.defaultQPB) sizeQL = QLabel(self.tr('Video Size:')) aspectQL = QLabel(self.tr('Aspect:')) frameQL = QLabel(self.tr('Frame Rate (fps):')) bitrateQL = QLabel(self.tr('Video Bitrate (kbps):')) self.widthQLE = utils.create_LineEdit((70, 16777215), digits_validator_minus, 4) self.heightQLE = utils.create_LineEdit((70, 16777215), digits_validator_minus, 4) label = QLabel('<html><p align="center">x</p></html>') layout1 = utils.add_to_layout('h', self.widthQLE, label, self.heightQLE) self.aspect1QLE = utils.create_LineEdit((50, 16777215), digits_validator, 2) self.aspect2QLE = utils.create_LineEdit((50, 16777215), digits_validator, 2) label = QLabel('<html><p align="center">:</p></html>') layout2 = utils.add_to_layout('h', self.aspect1QLE, label, self.aspect2QLE) self.frameQLE = utils.create_LineEdit((120, 16777215), digits_validator, 4) self.bitrateQLE = utils.create_LineEdit((130, 16777215), digits_validator, 6) labels = [sizeQL, aspectQL, frameQL, bitrateQL] widgets = [layout1, layout2, self.frameQLE, self.bitrateQLE] self.preserveaspectQChB = QCheckBox(self.tr("Preserve aspect ratio")) self.preservesizeQChB = QCheckBox(self.tr("Preserve video size")) preserve_layout = utils.add_to_layout('v', self.preserveaspectQChB, self.preservesizeQChB) videosettings_layout = QHBoxLayout() for a, b in zip(labels, widgets): a.setText('<html><p align="center">{0}</p></html>'.format( a.text())) layout = utils.add_to_layout('v', a, b) videosettings_layout.addLayout(layout) if a == aspectQL: # add vidaspectCB in layout after aspectQL videosettings_layout.addLayout(preserve_layout) freqQL = QLabel(self.tr('Frequency (Hz):')) chanQL = QLabel(self.tr('Audio Channels:')) bitrateQL = QLabel(self.tr('Audio Bitrate (kbps):')) threadsQL = QLabel(self.tr('Threads:')) self.freqQCB = QComboBox() self.freqQCB.addItems(frequency_values) self.chan1QRB = QRadioButton('1') self.chan1QRB.setMaximumSize(QSize(51, 16777215)) self.chan2QRB = QRadioButton('2') self.chan2QRB.setMaximumSize(QSize(51, 16777215)) self.group = QButtonGroup() self.group.addButton(self.chan1QRB) self.group.addButton(self.chan2QRB) spcr1 = QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Minimum) spcr2 = QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Minimum) chanlayout = utils.add_to_layout('h', spcr1, self.chan1QRB, self.chan2QRB, spcr2) self.audbitrateQCB = QComboBox() self.audbitrateQCB.addItems(bitrate_values) self.threadsQLE = utils.create_LineEdit((50, 16777215), digits_validator_wzero, 1) labels = [freqQL, bitrateQL, chanQL, threadsQL] widgets = [ self.freqQCB, self.audbitrateQCB, chanlayout, self.threadsQLE ] audiosettings_layout = QHBoxLayout() for a, b in zip(labels, widgets): a.setText('<html><p align="center">{0}</p></html>'.format( a.text())) layout = utils.add_to_layout('v', a, b) audiosettings_layout.addLayout(layout) time_format = " (hh:mm:ss):" beginQL = QLabel(self.tr("Split file. Begin time") + time_format) self.beginQLE = utils.create_LineEdit(None, time_validator, None) durationQL = QLabel(self.tr("Duration") + time_format) self.durationQLE = utils.create_LineEdit(None, time_validator, None) hlayout4 = utils.add_to_layout('h', beginQL, self.beginQLE, durationQL, self.durationQLE) embedQL = QLabel(self.tr("Embed subtitle:")) self.embedQLE = QLineEdit() self.embedQTB = QToolButton() self.embedQTB.setText("...") rotateQL = QLabel(self.tr("Rotate:")) self.rotateQCB = QComboBox() self.rotateQCB.addItems(rotation_options) hlayout5 = utils.add_to_layout('h', rotateQL, self.rotateQCB, embedQL, self.embedQLE, self.embedQTB) hidden_layout = utils.add_to_layout('v', videosettings_layout, audiosettings_layout, hlayout4, hlayout5) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.moreQPB = QPushButton(QApplication.translate('Tab', 'More')) self.moreQPB.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.moreQPB.setCheckable(True) hlayout3 = utils.add_to_layout('h', line, self.moreQPB) self.frame = QFrame() self.frame.setLayout(hidden_layout) self.frame.hide() final_layout = utils.add_to_layout('v', hlayout1, hlayout2, hlayout3, self.frame) self.setLayout(final_layout) self.presetQPB.clicked.connect(self.choose_preset) self.defaultQPB.clicked.connect(self.set_default_command) self.embedQTB.clicked.connect(self.open_subtitle_file) self.moreQPB.toggled.connect(self.frame.setVisible) self.moreQPB.toggled.connect( lambda: QTimer.singleShot(100, self.resize_parent)) self.widthQLE.textChanged.connect(self.command_update_size) self.heightQLE.textChanged.connect(self.command_update_size) self.aspect1QLE.textChanged.connect(self.command_update_aspect) self.aspect2QLE.textChanged.connect(self.command_update_aspect) self.frameQLE.textChanged.connect(self.command_update_frames) self.bitrateQLE.textChanged.connect(self.command_update_vidbitrate) self.threadsQLE.textChanged.connect(self.command_update_threads) self.beginQLE.textChanged.connect(self.command_update_begin_time) self.durationQLE.textChanged.connect(self.command_update_duration) self.embedQLE.textChanged.connect(self.command_update_subtitles) self.vidcodecQCB.currentIndexChanged.connect( self.command_update_vcodec) self.audcodecQCB.currentIndexChanged.connect( self.command_update_acodec) self.freqQCB.currentIndexChanged.connect(self.command_update_frequency) self.rotateQCB.currentIndexChanged.connect( self.command_update_rotation) self.audbitrateQCB.currentIndexChanged.connect( self.command_update_audbitrate) self.chan1QRB.clicked.connect( lambda: self.command_update_channels('1')) self.chan2QRB.clicked.connect( lambda: self.command_update_channels('2')) self.preserveaspectQChB.toggled.connect( self.command_update_preserve_aspect) self.preservesizeQChB.toggled.connect( self.command_update_preserve_size)
def __init__(self, parent=None): ''' Constructor ''' QWidget.__init__(self, parent) self.mainLayout = QVBoxLayout() self.setLayout(self.mainLayout) self.addTalkGroupBox = QGroupBox("Add Talk") self.mainLayout.addWidget(self.addTalkGroupBox) self.addTalkLayout = QFormLayout() self.addTalkGroupBox.setLayout(self.addTalkLayout) # Title self.titleLabel = QLabel("Title") self.titleLineEdit = QLineEdit() if hasattr(QLineEdit(), 'setPlaceholderText'): self.titleLineEdit.setPlaceholderText("Title of the presentation") self.titleLabel.setBuddy(self.titleLineEdit) self.addTalkLayout.addRow(self.titleLabel, self.titleLineEdit) # Presenter self.presenterLabel = QLabel("Presenter") self.presenterLineEdit = QLineEdit() if hasattr(QLineEdit(), 'setPlaceholderText'): self.presenterLineEdit.setPlaceholderText( "Name person or people presenting (comma separated)") self.presenterLabel.setBuddy(self.presenterLineEdit) self.addTalkLayout.addRow(self.presenterLabel, self.presenterLineEdit) # Event self.eventLabel = QLabel("Event") self.eventLineEdit = QLineEdit() if hasattr(QLineEdit(), 'setPlaceholderText'): self.eventLineEdit.setPlaceholderText( "The name of the Event this talk is being presented at") self.eventLabel.setBuddy(self.eventLineEdit) self.addTalkLayout.addRow(self.eventLabel, self.eventLineEdit) # Room self.roomLabel = QLabel("Room") self.roomLineEdit = QLineEdit() if hasattr(QLineEdit(), 'setPlaceholderText'): self.roomLineEdit.setPlaceholderText( "The Room in which the presentation is taking place") self.roomLabel.setBuddy(self.roomLineEdit) self.addTalkLayout.addRow(self.roomLabel, self.roomLineEdit) # Date current_date = QDate() self.dateLabel = QLabel("Date") self.dateEdit = QDateEdit() self.dateEdit.setDate(current_date.currentDate()) self.dateLabel.setBuddy(self.dateEdit) self.addTalkLayout.addRow(self.dateLabel, self.dateEdit) self.dateEdit.setCalendarPopup(True) # Time current_time = QTime() self.timeLabel = QLabel("Time") self.timeEdit = QTimeEdit() self.timeEdit.setTime(current_time.currentTime()) self.timeLabel.setBuddy(self.dateEdit) self.addTalkLayout.addRow(self.timeLabel, self.timeEdit) # Buttons addIcon = QIcon.fromTheme("list-add") cancelIcon = QIcon.fromTheme("edit-clear") self.buttonsWidget = QHBoxLayout() self.addButton = QPushButton("Add") self.addButton.setIcon(addIcon) self.cancelButton = QPushButton("Cancel") self.cancelButton.setIcon(cancelIcon) self.buttonsWidget.addWidget(self.addButton) self.buttonsWidget.addWidget(self.cancelButton) self.addTalkLayout.addRow(None, self.buttonsWidget)
def __init__(self, configFile, rowCount, verifyWindowDict, parent=None): super(VerifySetpoint, self).__init__(parent, Qt.CustomizeWindowHint | Qt.WindowTitleHint) self.configFile = configFile self.rowCount = rowCount self.verifyWindowDict = verifyWindowDict self.setWindowTitle('%s: setpoint v.s. readback' % self.configFile.split('/')[-1]) resolution = QDesktopWidget().screenGeometry() #self.setGeometry(resolution.width(), resolution.height() ,250, 150) self.setGeometry(resolution.width(), 0, 250, 150) self.startUpdate = 1 self.keys = [] fd = open(self.configFile) lines = fd.readlines() #print(lines) setpointPVList = [] readbackPVList = [] self.allPVList = [] #thresholdList = [] rampRatePVList = [] for line in lines: #print(line.split()) setpointPVList.append(str(line.split()[0])) readbackPVList.append(str(line.split()[1])) if len(line.split()) > 2: #thresholdList.append(str(line.split()[2])) rampRatePVList.append(str(line.split()[2])) self.allPVList = setpointPVList + readbackPVList + rampRatePVList self.pvListColumn = 3 #print(setpointPVList) #print(readbackPVList) #print(self.allPVList) #print(thresholdList) #print(rampRatePVList) layout = QGridLayout(self) self.label = QLabel() if self.rowCount > len(readbackPVList): self.label.setText( "%d PVs in the original snapshot, but only %d pairs of setpoint &\ readback PVs in this table because some setpoint PVs don't have readbacks\n\nPlease click the \ button below to update data\n" % (self.rowCount, len(readbackPVList))) else: self.label.setText( "%d pairs of setpoint & readback PVs in this table\n\n \ Please click the button below to update data\n" % (len(readbackPVList))) layout.addWidget(self.label, 0, 0, 1, 2) self.table = QTableWidget() sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.table.sizePolicy().hasHeightForWidth()) self.table.setSizePolicy(sizePolicy) self.table.setMinimumSize(QSize(700, 500)) self.table.resize(self.table.sizeHint()) self.table.setRowCount(len(setpointPVList)) #if len(thresholdList): if len(rampRatePVList): #self.keys = ['setpoint PV','readback PV','SP value','RB value','diff', 'threshold'] self.keys = [ 'setpoint PV', 'readback PV', 'SP value (Amp)', 'RB value (Amp)', 'diff', 'ramp-rate (Amp/Sec)' ] else: self.keys = [ 'setpoint PV', 'readback PV', 'SP value', 'RB value', 'diff' ] self.table.setColumnCount(len(self.keys)) self.table.setHorizontalHeaderLabels(self.keys) layout.addWidget(self.table, 1, 0, 1, 2) #======================================================================= # toggleButton = QPushButton('Updating started', self) # toggleButton.clicked.connect(self.toggle) # layout.addWidget(toggleButton, 2, 0, 1, 1) #======================================================================= updateButton = QPushButton('Update Table', self) updateButton.clicked.connect(self.updateTable) layout.addWidget(updateButton, 2, 0, 1, 1) self.quit = QPushButton('Close Widget', self) #self.connect(self.quit, SIGNAL('clicked()'), self.close) #self.destroyed.connect(self.cleanup()) #self.deleteLater.connect(self.cleanup()) self.connect(self.quit, SIGNAL('clicked()'), self.cleanup) layout.addWidget(self.quit, 2, 1, 1, 1) self.setLayout(layout) #self.timer = cothread.Timer(2, self.updateTable, retrigger=True, reuse=True) self.updateTable()
class TextBoxPanel(QWidget): def __init__(self, parent, isArea=False): QWidget.__init__(self, parent) while not isinstance(parent, QDialog): parent = parent.parent() self.setObjectName("TextBoxPanel" + str(len(parent.findChildren(TextBoxPanel)))) self.hLayoutBoxPanel = QHBoxLayout(self) self.hLayoutBoxPanel.setSpacing(0) self.hLayoutBoxPanel.setContentsMargins(0, 0, 0, 0) self.hLayoutBoxPanel.setObjectName(("hLayoutBoxPanel")) self.frameBoxPanel = QFrame(self) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.frameBoxPanel.sizePolicy().hasHeightForWidth()) self.frameBoxPanel.setSizePolicy(sizePolicy) self.frameBoxPanel.setFrameShape(QFrame.NoFrame) self.frameBoxPanel.setFrameShadow(QFrame.Raised) self.frameBoxPanel.setObjectName(("frameBoxPanel")) self.hLayoutframeBoxPanel = QHBoxLayout(self.frameBoxPanel) self.hLayoutframeBoxPanel.setSpacing(0) self.hLayoutframeBoxPanel.setMargin(0) self.hLayoutframeBoxPanel.setObjectName(("hLayoutframeBoxPanel")) self.captionLabel = QLabel(self.frameBoxPanel) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.captionLabel.sizePolicy().hasHeightForWidth()) self.captionLabel.setSizePolicy(sizePolicy) self.captionLabel.setMinimumSize(QSize(200, 0)) self.captionLabel.setMaximumSize(QSize(200, 16777215)) font = QFont() font.setBold(False) font.setWeight(50) self.captionLabel.setFont(font) self.captionLabel.setObjectName(("captionLabel")) self.hLayoutframeBoxPanel.addWidget(self.captionLabel) if not isArea: self.textBox = QLineEdit(self.frameBoxPanel) self.textBox.setEnabled(True) font = QFont() font.setBold(False) font.setWeight(50) self.textBox.setFont(font) self.textBox.setObjectName(("textBox")) self.textBox.setMinimumWidth(70) self.textBox.setMaximumWidth(70) # self.textBox.setText("0.0") self.hLayoutframeBoxPanel.addWidget(self.textBox) else: self.textBox = QTextEdit(self.frameBoxPanel) self.textBox.setEnabled(True) font = QFont() font.setBold(False) font.setWeight(50) self.textBox.setFont(font) self.textBox.setObjectName(("textBox")) # self.textBox.setText("0.0") self.textBox.setMaximumHeight(60) self.hLayoutframeBoxPanel.addWidget(self.textBox) self.imageButton = QPushButton(self.frameBoxPanel) self.imageButton.setText(("")) icon = QIcon() icon.addPixmap(QPixmap(("Resource/convex_hull.png")), QIcon.Normal, QIcon.Off) self.imageButton.setIcon(icon) self.imageButton.setObjectName(("imageButton")) self.imageButton.setVisible(False) self.hLayoutframeBoxPanel.addWidget(self.imageButton) self.hLayoutBoxPanel.addWidget(self.frameBoxPanel) self.spacerItem = QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum) self.hLayoutframeBoxPanel.addItem(self.spacerItem) self.textBox.textChanged.connect(self.textBoxChanged) self.imageButton.clicked.connect(self.imageButtonClicked) self.textBox.setText("") self.captionUnits = "" self.isArea = isArea def method_2(self, string0): self.textBox.setText(string0) def method_8(self, string_0): return "%s%s\t%s" % (string_0, self.Caption, self.Value) def textBoxChanged(self): self.emit(SIGNAL("Event_0"), self) def imageButtonClicked(self): self.emit(SIGNAL("Event_1"), self) def get_Caption(self): caption = self.captionLabel.text() findIndex = caption.indexOf("(") if findIndex > 0: val = caption.left(findIndex) return val return caption def set_Caption(self, captionStr): if captionStr == "": self.captionLabel.setText("") self.LabelWidth = 0 return if self.CaptionUnits != "" and self.CaptionUnits != None: self.captionLabel.setText(captionStr + "(" + str(self.CaptionUnits) + ")" + ":") else: self.captionLabel.setText(captionStr + ":") Caption = property(get_Caption, set_Caption, None, None) def get_CaptionUnits(self): return self.captionUnits def set_CaptionUnits(self, captionUnits): self.captionUnits = captionUnits CaptionUnits = property(get_CaptionUnits, set_CaptionUnits, None, None) def set_ButtonVisible(self, bool): self.imageButton.setVisible(bool) ButtonVisible = property(None, set_ButtonVisible, None, None) def get_Value(self): if not self.isArea: return self.textBox.text() else: return self.textBox.toPlainText() def set_Value(self, valueStr): try: self.textBox.setText(valueStr) except: self.textBox.setText("") Value = property(get_Value, set_Value, None, None) Text = property(get_Value, set_Value, None, None) def get_IsEmpty(self): return self.textBox.text() == "" or self.textBox.text() == None IsEmpty = property(get_IsEmpty, None, None, None) def get_ReadOnly(self): return self.textBox.isReadOnly() def set_ReadOnly(self, bool): self.textBox.setReadOnly(bool) ReadOnly = property(get_ReadOnly, set_ReadOnly, None, None) def set_LabelWidth(self, width): self.captionLabel.setMinimumSize(QSize(width, 0)) self.captionLabel.setMaximumSize(QSize(width, 16777215)) LabelWidth = property(None, set_LabelWidth, None, None) def get_Enabled(self): return self.textBox.isEnabled() def set_Enabled(self, bool): self.textBox.setEnabled(bool) Enabled = property(get_Enabled, set_Enabled, None, None) def get_Visible(self): return self.isVisible() def set_Visible(self, bool): self.setVisible(bool) Visible = property(get_Visible, set_Visible, None, None) def set_Button(self, imageName): if imageName == None or imageName == "": self.imageButton.setVisible(False) return icon = QIcon() icon.addPixmap(QPixmap(("Resource/" + imageName)), QIcon.Normal, QIcon.Off) self.imageButton.setIcon(icon) self.imageButton.setVisible(True) Button = property(None, set_Button, None, None) def set_Width(self, val): try: self.textBox.setMaximumWidth(val) self.textBox.setMinimumWidth(val) except: pass Width = property(None, set_Width, None, None) def set_EchoMode(self, value): if value == "Password": self.textBox.setEchoMode(QLineEdit.Password) EchoMode = property(None, set_EchoMode, None, None)
class ImportWizard(QDialog): """Text data import wizard""" def __init__(self, parent, text, title=None, icon=None, contents_title=None, varname=None): QDialog.__init__(self, parent) # Destroying the C++ object right after closing the dialog box, # otherwise it may be garbage-collected in another QThread # (e.g. the editor's analysis thread in Spyder), thus leading to # a segmentation fault on UNIX or an application crash on Windows self.setAttribute(Qt.WA_DeleteOnClose) if title is None: title = _("Import wizard") self.setWindowTitle(title) if icon is None: self.setWindowIcon(get_icon("fileimport.png")) if contents_title is None: contents_title = _("Raw text") if varname is None: varname = _("variable_name") self.var_name, self.clip_data = None, None # Setting GUI self.tab_widget = QTabWidget(self) self.text_widget = ContentsWidget(self, text) self.table_widget = PreviewWidget(self) self.tab_widget.addTab(self.text_widget, _("text")) self.tab_widget.setTabText(0, contents_title) self.tab_widget.addTab(self.table_widget, _("table")) self.tab_widget.setTabText(1, _("Preview")) self.tab_widget.setTabEnabled(1, False) name_layout = QHBoxLayout() name_h_spacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) name_layout.addItem(name_h_spacer) name_label = QLabel(_("Name")) name_layout.addWidget(name_label) self.name_edt = QLineEdit() self.name_edt.setMaximumWidth(100) self.name_edt.setText(varname) name_layout.addWidget(self.name_edt) btns_layout = QHBoxLayout() cancel_btn = QPushButton(_("Cancel")) btns_layout.addWidget(cancel_btn) self.connect(cancel_btn, SIGNAL("clicked()"), self, SLOT("reject()")) h_spacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) btns_layout.addItem(h_spacer) self.back_btn = QPushButton(_("Previous")) self.back_btn.setEnabled(False) btns_layout.addWidget(self.back_btn) self.connect(self.back_btn, SIGNAL("clicked()"), ft_partial(self._set_step, step=-1)) self.fwd_btn = QPushButton(_("Next")) btns_layout.addWidget(self.fwd_btn) self.connect(self.fwd_btn, SIGNAL("clicked()"), ft_partial(self._set_step, step=1)) self.done_btn = QPushButton(_("Done")) self.done_btn.setEnabled(False) btns_layout.addWidget(self.done_btn) self.connect(self.done_btn, SIGNAL("clicked()"), self, SLOT("process()")) self.connect(self.text_widget, SIGNAL("asDataChanged(bool)"), self.fwd_btn, SLOT("setEnabled(bool)")) self.connect(self.text_widget, SIGNAL("asDataChanged(bool)"), self.done_btn, SLOT("setDisabled(bool)")) layout = QVBoxLayout() layout.addLayout(name_layout) layout.addWidget(self.tab_widget) layout.addLayout(btns_layout) self.setLayout(layout) def _focus_tab(self, tab_idx): """Change tab focus""" for i in range(self.tab_widget.count()): self.tab_widget.setTabEnabled(i, False) self.tab_widget.setTabEnabled(tab_idx, True) self.tab_widget.setCurrentIndex(tab_idx) def _set_step(self, step): """Proceed to a given step""" new_tab = self.tab_widget.currentIndex() + step assert new_tab < self.tab_widget.count() and new_tab >= 0 if new_tab == self.tab_widget.count() - 1: try: self.table_widget.open_data( self._get_plain_text(), self.text_widget.get_col_sep(), self.text_widget.get_row_sep(), self.text_widget.trnsp_box.isChecked(), self.text_widget.get_skiprows(), self.text_widget.get_comments()) self.done_btn.setEnabled(True) self.done_btn.setDefault(True) self.fwd_btn.setEnabled(False) self.back_btn.setEnabled(True) except (SyntaxError, AssertionError), error: QMessageBox.critical( self, _("Import wizard"), _("<b>Unable to proceed to next step</b>" "<br><br>Please check your entries." "<br><br>Error message:<br>%s") % str(error)) return elif new_tab == 0: self.done_btn.setEnabled(False) self.fwd_btn.setEnabled(True) self.back_btn.setEnabled(False)
def __init__(self, data, win_parent=None): """ +-----------------+ | Edit Node Props | +-----------------+------+ | LEwingTip | | Node2 | | Node3 | | Node4 | | | | All Nodes: | | Color red | | PointSize 3 | | Opacity 0.3 | | Show/Hide | | | | Name LEwingTip | | Location X Y Z | | Coord 0 | | CoordType R, C, S | | | | Previous Next | | | | Close | +------------------------+ """ QDialog.__init__(self, win_parent) self.setWindowTitle('Edit Node Properties') #default self.win_parent = win_parent self.out_data = data point_properties = data['point_properties'] print(point_properties) #name = point_properties.name point_size = point_properties.point_size opacity = point_properties.opacity color = point_properties.color show = point_properties.is_visible self.points = data['points'] self.keys = sorted(self.points.keys()) keys = self.keys #nrows = len(keys) active_point = data['active_point'] #self.active_key = keys[0] self.active_key = active_point name = self.active_key description = self.points[self.active_key][0] self._use_old_table = False items = ['Node %i' % val for val in keys] header_labels = ['Nodes'] table_model = Model(items, header_labels, self) view = SingleChoiceQTableView(self) #Call your custom QTableView here view.setModel(table_model) if qt_version in [4, 'pyside']: view.horizontalHeader().setResizeMode(QHeaderView.Stretch) else: view.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) self.table = view #self.representation = actor_obj.representation #print('rep =', self.representation) table = self.table #headers = [QtCore.QString('Groups')] header = table.horizontalHeader() header.setStretchLastSection(True) #---------------------------------------------- #self._default_is_apply = False self.color = QLabel("Color:") self.color_edit = QPushButton() #self.color_edit.setFlat(True) color = self.out_data['point_properties'].color opacity = self.out_data['point_properties'].opacity show = self.out_data['point_properties'].is_visible #color = self.out_data[self.active_key].color qcolor = QColor() qcolor.setRgb(*color) #print('color =%s' % str(color)) palette = QPalette( self.color_edit.palette()) # make a copy of the palette #palette.setColor(QPalette.Active, QPalette.Base, \ #qcolor) palette.setColor(QPalette.Background, QColor('blue')) # ButtonText self.color_edit.setPalette(palette) self.color_edit.setStyleSheet("QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(color) + #"border:1px solid rgb(255, 170, 255); " "}") self.all_nodes_header = QLabel("All Nodes:") self.point_size = QLabel("Point Size:") self.point_size_edit = QSpinBox(self) self.point_size_edit.setRange(1, 10) self.point_size_edit.setSingleStep(1) self.point_size_edit.setValue(point_size) self.opacity = QLabel("Opacity:") self.opacity_edit = QDoubleSpinBox(self) self.opacity_edit.setRange(0.1, 1.0) self.opacity_edit.setDecimals(1) self.opacity_edit.setSingleStep(0.1) self.opacity_edit.setValue(opacity) # show/hide self.checkbox_show = QCheckBox("Show") self.checkbox_hide = QCheckBox("Hide") self.checkbox_show.setChecked(show) self.checkbox_hide.setChecked(not show) #---------------------------------------------- self.nodes_header = QLabel("Single Node:") self.name = QLabel("ID:") self.name_edit = QLineEdit('Node %i' % name) self.name_edit.setDisabled(True) self.description = QLabel("Description:") self.description_edit = QLineEdit(str(description)) #self.description_edit.setDisabled(True) location_x = 0.1 location_y = 0.1 location_z = 0.1 self.location = QLabel("Location:") self.location_x_edit = QDoubleSpinBox(self) self.location_y_edit = QDoubleSpinBox(self) self.location_z_edit = QDoubleSpinBox(self) #self.location_x_edit.setDecimals(1) delta_x = abs(location_x) / 100. if location_x != 0.0 else 0.1 delta_y = abs(location_y) / 100. if location_y != 0.0 else 0.1 delta_z = abs(location_z) / 100. if location_z != 0.0 else 0.1 self.location_x_edit.setSingleStep(delta_x) self.location_y_edit.setSingleStep(delta_y) self.location_z_edit.setSingleStep(delta_z) self.location_x_edit.setValue(location_x) self.location_y_edit.setValue(location_y) self.location_z_edit.setValue(location_z) self.coord = QLabel("Coord:") self.coord_edit = QSpinBox(self) self.coord_edit.setRange(0, 99999999) #self.coord_edit.setSingleStep(1) self.coord_edit.setValue(0) self.coord_type = QLabel("Coord Type:") #---------------------------------------------- # closing #if self._default_is_apply: #self.apply_button.setDisabled(True) self.close_button = QPushButton("Close") self.create_layout() self.set_connections()
def __init__(self, parent, isArea=False): QWidget.__init__(self, parent) while not isinstance(parent, QDialog): parent = parent.parent() self.setObjectName("TextBoxPanel" + str(len(parent.findChildren(TextBoxPanel)))) self.hLayoutBoxPanel = QHBoxLayout(self) self.hLayoutBoxPanel.setSpacing(0) self.hLayoutBoxPanel.setContentsMargins(0, 0, 0, 0) self.hLayoutBoxPanel.setObjectName(("hLayoutBoxPanel")) self.frameBoxPanel = QFrame(self) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.frameBoxPanel.sizePolicy().hasHeightForWidth()) self.frameBoxPanel.setSizePolicy(sizePolicy) self.frameBoxPanel.setFrameShape(QFrame.NoFrame) self.frameBoxPanel.setFrameShadow(QFrame.Raised) self.frameBoxPanel.setObjectName(("frameBoxPanel")) self.hLayoutframeBoxPanel = QHBoxLayout(self.frameBoxPanel) self.hLayoutframeBoxPanel.setSpacing(0) self.hLayoutframeBoxPanel.setMargin(0) self.hLayoutframeBoxPanel.setObjectName(("hLayoutframeBoxPanel")) self.captionLabel = QLabel(self.frameBoxPanel) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.captionLabel.sizePolicy().hasHeightForWidth()) self.captionLabel.setSizePolicy(sizePolicy) self.captionLabel.setMinimumSize(QSize(200, 0)) self.captionLabel.setMaximumSize(QSize(200, 16777215)) font = QFont() font.setBold(False) font.setWeight(50) self.captionLabel.setFont(font) self.captionLabel.setObjectName(("captionLabel")) self.hLayoutframeBoxPanel.addWidget(self.captionLabel) if not isArea: self.textBox = QLineEdit(self.frameBoxPanel) self.textBox.setEnabled(True) font = QFont() font.setBold(False) font.setWeight(50) self.textBox.setFont(font) self.textBox.setObjectName(("textBox")) self.textBox.setMinimumWidth(70) self.textBox.setMaximumWidth(70) # self.textBox.setText("0.0") self.hLayoutframeBoxPanel.addWidget(self.textBox) else: self.textBox = QTextEdit(self.frameBoxPanel) self.textBox.setEnabled(True) font = QFont() font.setBold(False) font.setWeight(50) self.textBox.setFont(font) self.textBox.setObjectName(("textBox")) # self.textBox.setText("0.0") self.textBox.setMaximumHeight(60) self.hLayoutframeBoxPanel.addWidget(self.textBox) self.imageButton = QPushButton(self.frameBoxPanel) self.imageButton.setText(("")) icon = QIcon() icon.addPixmap(QPixmap(("Resource/convex_hull.png")), QIcon.Normal, QIcon.Off) self.imageButton.setIcon(icon) self.imageButton.setObjectName(("imageButton")) self.imageButton.setVisible(False) self.hLayoutframeBoxPanel.addWidget(self.imageButton) self.hLayoutBoxPanel.addWidget(self.frameBoxPanel) self.spacerItem = QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum) self.hLayoutframeBoxPanel.addItem(self.spacerItem) self.textBox.textChanged.connect(self.textBoxChanged) self.imageButton.clicked.connect(self.imageButtonClicked) self.textBox.setText("") self.captionUnits = "" self.isArea = isArea
def __init__(self, parent=None): QWidget.__init__(self, parent) vbox = QVBoxLayout(self) vbox.setContentsMargins(0, 0, 0, 0) vbox.setSpacing(0) self.__toolbar = QToolBar() self.__toolbar.setObjectName('custom') hbox = QHBoxLayout() vbox.addLayout(hbox) self.stack = StackedWidget() vbox.addWidget(self.stack) self._console = console_widget.ConsoleWidget() self.stack.addWidget(self._console) self._runWidget = run_widget.RunWidget() self.stack.addWidget(self._runWidget) self._web = web_render.WebRender() self.stack.addWidget(self._web) self._findInFilesWidget = find_in_files.FindInFilesWidget( self.parent()) self.stack.addWidget(self._findInFilesWidget) #Last Element in the Stacked widget self._results = results.Results(self) self.stack.addWidget(self._results) self._btnConsole = QPushButton(QIcon(resources.IMAGES['console']), '') self._btnConsole.setToolTip(self.tr("Console")) self._btnRun = QPushButton(QIcon(resources.IMAGES['play']), '') self._btnRun.setToolTip(self.tr("Output")) self._btnWeb = QPushButton(QIcon(resources.IMAGES['web']), '') self._btnWeb.setToolTip(self.tr("Web Preview")) self._btnFind = QPushButton(QIcon(resources.IMAGES['find']), '') self._btnFind.setToolTip(self.tr("Find in Files")) #Toolbar hbox.addWidget(self.__toolbar) self.__toolbar.addWidget(self._btnConsole) self.__toolbar.addWidget(self._btnRun) self.__toolbar.addWidget(self._btnWeb) self.__toolbar.addWidget(self._btnFind) self.__toolbar.addSeparator() hbox.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding)) btn_close = QPushButton( self.style().standardIcon(QStyle.SP_DialogCloseButton), '') btn_close.setObjectName('navigation_button') btn_close.setToolTip(self.tr('F4: Show/Hide')) hbox.addWidget(btn_close) self.connect(self._btnConsole, SIGNAL("clicked()"), lambda: self._item_changed(0)) self.connect(self._btnRun, SIGNAL("clicked()"), lambda: self._item_changed(1)) self.connect(self._btnWeb, SIGNAL("clicked()"), lambda: self._item_changed(2)) self.connect(self._btnFind, SIGNAL("clicked()"), lambda: self._item_changed(3)) self.connect(btn_close, SIGNAL('clicked()'), self.hide)
class EditPane(QWidget): def __init__(self, model): QWidget.__init__(self) self._setupUi() self.model = model self.model.view = self self.normalButton.clicked.connect( partial(self.model.app.change_state_of_selected, ElementState.Normal)) self.titleButton.clicked.connect( partial(self.model.app.change_state_of_selected, ElementState.Title)) self.footnoteButton.clicked.connect( partial(self.model.app.change_state_of_selected, ElementState.Footnote)) self.ignoreButton.clicked.connect( partial(self.model.app.change_state_of_selected, ElementState.Ignored)) self.tofixButton.clicked.connect( partial(self.model.app.change_state_of_selected, ElementState.ToFix)) self.hideIgnoredCheckBox.stateChanged.connect( self.hideIgnoredCheckBoxStateChanged) self.textEdit.textChanged.connect(self.textEditTextChanged) self.saveEditsButton.clicked.connect(self.model.save_edits) self.cancelEditsButton.clicked.connect(self.model.cancel_edits) def _setupUi(self): self.mainLayout = QVBoxLayout(self) self.buttonLayout = QGridLayout() self.normalButton = QPushButton("Normal") self.buttonLayout.addWidget(self.normalButton, 0, 0) self.titleButton = QPushButton("Title") self.buttonLayout.addWidget(self.titleButton, 1, 0) self.footnoteButton = QPushButton("Footnote") self.buttonLayout.addWidget(self.footnoteButton, 2, 0) self.ignoreButton = QPushButton("Ignore") self.buttonLayout.addWidget(self.ignoreButton, 0, 1) self.tofixButton = QPushButton("To Fix") self.buttonLayout.addWidget(self.tofixButton, 1, 1) self.mainLayout.addLayout(self.buttonLayout) self.rightLayout = QVBoxLayout() self.hideIgnoredCheckBox = QCheckBox("Hide Ignored Elements") self.rightLayout.addWidget(self.hideIgnoredCheckBox) self.textEdit = QTextEdit() self.textEdit.setAcceptRichText(False) self.rightLayout.addWidget(self.textEdit) self.editButtonLayout = QHBoxLayout() self.editButtonLayout.addItem(horizontalSpacer()) self.saveEditsButton = QPushButton("Save") self.editButtonLayout.addWidget(self.saveEditsButton) self.cancelEditsButton = QPushButton("Cancel") self.editButtonLayout.addWidget(self.cancelEditsButton) self.rightLayout.addLayout(self.editButtonLayout) self.mainLayout.addLayout(self.rightLayout) #--- Signals def hideIgnoredCheckBoxStateChanged(self, state): self.model.app.hide_ignored = state == Qt.Checked def textEditTextChanged(self): self.model.edit_text = self.textEdit.toPlainText() #--- model -> view def refresh_edit_text(self): self.textEdit.setText(self.model.edit_text) self.textEdit.setEnabled(self.model.edit_enabled) self.saveEditsButton.setEnabled(self.model.edit_enabled) self.cancelEditsButton.setEnabled(self.model.edit_enabled)
class MainWindow(QMainWindow): SHUTDOWN_MENU = "&Shutdown" HELP_MENU = "&Help" SOFT_EXIT = "&Soft Exit" PHONE_HOME = "Pho&ne Home" ADD_MENU = "Add &Pattern" DELETE_MENU = "&Delete" VERSION_MENU = "&Version" ABOUT_MENU = "&About" ## __init__ --------------------------------------------------------- def __init__(self, Log=None): # Make Main window QMainWindow.__init__(self, None) self.setWindowTitle("Lightbox") self.resize(800, 480) # Screen Size self.__log = Log self.CALLING_CLASS = "MainWindow" if self.__log == None: print "No Log File" self.close() # Create main layout for window mainWidget = QWidget(self) self.__mainLayout = QVBoxLayout(mainWidget) mainWidget.setLayout(self.__mainLayout) # Selected pattern self.__selectedPattern = None self.__presetPatternForDeleting = None self.__currentIntensity = 4000 self.__loadedPattern = None ## Loaded (Running Pattern) self.__loadedPatternBeforePreset = None self.__CACHED_PRESET = None self.EXECUTION_THREAD = None # Add Menu Bard self.__menu = self.__createMenu() ## Toolbar that is always there->Selected Pattern, Start, Stop, Current State Label self.__statusLayout = self.__createStatusLayout() self.__mainLayout.addLayout(self.__statusLayout) self.__patterns = list() self.__buttons = list() self.__savedPresets = list() self.__presetManager = PresetManager(self.__log) self.__defaultButtonLayout = QVBoxLayout() self.__selectedPatternLayout = QVBoxLayout() self.__intensitySelectLayout = QVBoxLayout() self.__presetButtonLayout = QVBoxLayout() self.__makeDefaultButtons() self.__importPresetsFromFile() # Connect TagPushButton signals self.connect(self, SIGNAL("tagPushButtonClicked(PyQt_PyObject)"), self._tagButtonClicked) self.connect(self, SIGNAL("idPushButtonClicked(PyQt_PyObject)"), self._idButtonClicked) # Make the window knwo what is the main widget self.setCentralWidget(mainWidget) self.ColorIcons = [QIcon(RED_ICON_LOC), QIcon(REDOR_ICON_LOC), QIcon(CYAN_ICON_LOC), QIcon(GREEN_ICON_LOC), QIcon(BLUE_ICON_LOC), QIcon(WHITE_ICON_LOC), \ QIcon(YELLOW_ICON_LOC)] self.__mode = PATTERN_SELECT_MODE self.__lastMode = self.__mode self.__modeBeforeIntensity = None self.__running = False def __createStatusLayout(self): ## Make the currently running, start and stop button, running status self.__currentPatternLabel = QLabel(PATTERN_PREAMBLE + EMPTY_PATTERN_SELECTED) font = self.__currentPatternLabel.font() self.__setFont(self.__currentPatternLabel, CONTROL_LABEL_FONT_SIZE) self.__currentStatusLabel = QLabel(STATUS_PREAMBLE + STOPPED) self.__setFont(self.__currentStatusLabel, CONTROL_LABEL_FONT_SIZE) self.StartButton = QPushButton("Start") self.__setFont(self.StartButton, CONTROL_BUTTON_FONT_SIZE) self.StartButton.setMinimumSize(CONTROL_BUTTON_WIDTH, CONTROL_BUTTON_HEIGHT) startIcon = QIcon(START_ICON_LOC) stopIcon = QIcon(STOP_ICON_LOC) self.StartButton.setIcon(startIcon) self.StopButton = QPushButton("Stop") self.__setFont(self.StopButton, CONTROL_BUTTON_FONT_SIZE) self.StopButton.setIcon(stopIcon) self.StopButton.setMinimumSize(CONTROL_BUTTON_WIDTH, CONTROL_BUTTON_HEIGHT) self.StartButton.clicked.connect(self.__handleStart) self.StopButton.clicked.connect(self.__handleStop) # put on the first row of the left coloumn, first two of the right column controlLayout = QHBoxLayout() leftHandColumn = QVBoxLayout() rightHandColumn = QVBoxLayout() leftHandColumn.addWidget(self.__currentPatternLabel) rightHandColumn.addWidget(self.__currentStatusLabel) startStopLayout = QHBoxLayout() startStopLayout.addWidget(self.StartButton) startStopLayout.addWidget(self.StopButton) rightHandColumn.addLayout(startStopLayout) ## Make Intensity Layout self.__intensityLabel = QLabel(INTENSITY_PREAMBLE + str(self.__currentIntensity)) self.__setFont(self.__intensityLabel, CONTROL_LABEL_FONT_SIZE) self.__intensityButton = QPushButton("Set Intensity...") self.__setFont(self.__intensityButton, CONTROL_BUTTON_FONT_SIZE) self.__intensityButton.setMinimumSize(CONTROL_BUTTON_WIDTH * 2, CONTROL_BUTTON_HEIGHT) self.__intensityButton.setMaximumSize(CONTROL_BUTTON_WIDTH * 2, CONTROL_BUTTON_HEIGHT) self.__intensityButton.clicked.connect(self.__intensityButtonClicked) intensityIcon = QIcon(INTENSITY_ICON_LOC) self.__intensityButton.setIcon(intensityIcon) intensityLayout = QVBoxLayout() intensityLayout.addWidget(self.__intensityLabel) intensityLayout.addWidget(self.__intensityButton) # add intensity layout to left hand column leftHandColumn.addLayout(intensityLayout) # Add shutdown button self.ShutdownButton = QPushButton("Shutdown") self.__setFont(self.ShutdownButton, CONTROL_BUTTON_FONT_SIZE) self.ShutdownButton.setMinimumSize(160, CONTROL_BUTTON_HEIGHT) shutdownIcon = QIcon(SHUTDOWN_ICON_LOC) self.ShutdownButton.setIcon(shutdownIcon) self.ShutdownButton.clicked.connect(self.__shutdown) rightHandColumn.addWidget(self.ShutdownButton) infoBarLayout = QHBoxLayout() infoBarLayout.addLayout(leftHandColumn) infoBarLayout.addStretch(1) infoBarLayout.addLayout(rightHandColumn) return infoBarLayout def __Log(self, message): self.__log.LOG(self.CALLING_CLASS, message) def __createMenu(self): menu = self.menuBar() ## About Menu ---------------------------------------- aboutMenu = menu.addMenu(MainWindow.ABOUT_MENU) versionAction = QAction(menu) versionAction.setText(MainWindow.VERSION_MENU) versionAction.triggered.connect(self.__showAbout) aboutMenu.addAction(versionAction) ## Shutdown Menu ----------------------------------------- #shutdownMenu = menu.addMenu(MainWindow.SHUTDOWN_MENU) if ADD_PATTERN_ENABLED: newPatternAction = QAction(menu) newPatternAction.setText(MainWindow.ADD_MENU) newPatternAction.triggered.connect(self.__addPattern) deletePatternAction = QAction(menu) deletePatternAction.setText(MainWindow.DELETE_MENU) deletePatternAction.triggered.connect(self.__deletePattern) #shutdownMenu.addAction(newPatternAction) #shutdownMenu.addAction(deletePatternAction) #shutdownAction = QAction(menu) #shutdownAction.setText(MainWindow.SHUTDOWN_MENU) #shutdownAction.triggered.connect(self.__shutdown) #shutdownMenu.addAction(shutdownAction) ## Soft Exit Menu ------------------------------------ helpMenu = menu.addMenu(MainWindow.HELP_MENU) softExitAction = QAction(menu) softExitAction.setText(MainWindow.SOFT_EXIT) softExitAction.triggered.connect(self.__exit) helpMenu.addAction(softExitAction) if PHONE_HOME_ENABLED: phoneHomeAction = QAction(menu) phoneHomeAction.setText(MainWindow.PHONE_HOME) softExitAction.triggered.connect(self.__phoneHome) helpMenu.addAction(phoneHomeAction) def __showAbout(self): ret = QMessageBox.information(self, "Version Info", "Release: July 10, 2014") ## Make the Default pattern Buttons ---------------------------------------------- def __makeDefaultButtons(self): for iter in range(0, NUM_DEFAULT_PATTERNS): self.__Log("Making preset %d" % iter) pattern_params = DEFAULT_PATTERNS[iter] name = pattern_params[pIndex.Name] des = pattern_params[pIndex.Description] default = pattern_params[pIndex.Default] clist = pattern_params[pIndex.ColorList] reqColors = pattern_params[pIndex.RequiredColors] pwm = pattern_params[pIndex.PWM] newPattern = Pattern(name, des, default, clist, reqColors, pwm, self.__log) self.__patterns += [newPattern] self.__drawPatternButtons() def __importPresetsFromFile(self): self.__savedPresets = self.__presetManager.GetPresetPatterns() ## Clear Layouts ------------------------------------------------------------------ def __clearLayout(self, layout): if layout is not None: while layout.count(): item = layout.takeAt(0) widget = item.widget() if widget is not None: widget.hide() else: self.__clearLayout(item.layout()) def __intensityButtonClicked(self): self.__Log("Intensity Button Clicked") self.__lastMode = self.__mode self.__drawIntensityButtons() ## Color Button has been clicked ------------------------------------------------------- def _idButtonClicked(self, ID): ## Currently only Color buttons are using the ID Button self.__Log("ColorID: %d" % ID) if self.__mode == PATTERN_EDIT_MODE: ## Show color select. self.__currentColorSelection = ID - 1 self.__drawColorButtons() elif self.__mode == INTENSITY_SELECT_MODE: # Get the intensity selected self.__intensitySelected(ID) elif self.__mode == PATTERN_PRESET_SELECT_MODE: self.__presetPatternSelectedForStart(ID) #self.__drawPatternButtons() else: self.__Log("Bad Mode") def _tagButtonClicked(self, buttonTag): self.__Log("Button Tag: %s, mode: %s" % (buttonTag, self.__mode)) if self.__mode == PATTERN_SELECT_MODE: self.__patternSelected(buttonTag) elif self.__mode == PATTERN_EDIT_MODE: # Must be the back or OK buttons if buttonTag == "Back": self.__patternEditControlPressed(buttonTag) elif buttonTag == "Save as Preset": self.__savePatternAsPreset() else: self.__colorSelected(buttonTag) elif self.__mode == PATTERN_PRESET_SELECT_MODE: if buttonTag == "Back": if self.__loadedPatternBeforePreset != None and self.__presetPatternForDeleting != None: self.__Log("Both are not none") if self.__loadedPatternBeforePreset.GetName( ) != self.__presetPatternForDeleting.GetName( ) and self.__loadedPatternBeforePreset.GetColorString( ) != self.__presetPatternForDeleting.GetColorString(): self.__Log( "Setting preset back to the one it was before") self.__loadedPattern = self.__loadedPatternBeforePreset self.__loadedPatternBeforePreset = None self.__presetPatternForDeleting = None self.__loadedPatternBeforePreset = None self.__drawPatternButtons() if self.__loadedPattern != None: self.__currentPatternLabel.setText( PATTERN_PREAMBLE + self.__loadedPattern.GetName() + ' ' + self.__loadedPattern.GetColorString()) elif buttonTag == "Delete": self.__presetPatternForDeleting = self.__loadedPattern if self.__loadedPatternBeforePreset != None and self.__presetPatternForDeleting != None: self.__Log("Both are not none") if self.__loadedPatternBeforePreset.GetName( ) == self.__presetPatternForDeleting.GetName( ) and self.__loadedPatternBeforePreset.GetColorString( ) == self.__presetPatternForDeleting.GetColorString(): self.__Log("Deleting the currently loaded pattern") self.__loadedPatternBeforePreset = None self.__loadedPattern = None self.__currentPatternLabel.setText( PATTERN_PREAMBLE + EMPTY_PATTERN_SELECTED) else: self.__Log( "Setting the loaded pattern back to what it should be before delete occured" ) self.__loadedPattern = self.__loadedPatternBeforePreset self.__currentPatternLabel.setText( PATTERN_PREAMBLE + self.__loadedPattern.GetName() + ' ' + self.__loadedPattern.GetColorString()) elif self.__loadedPatternBeforePreset == None: self.__currentPatternLabel.setText(PATTERN_PREAMBLE + EMPTY_PATTERN_SELECTED) self.__loadedPattern = None else: self.__loadedPattern = self.__loadedPatternBeforePreset self.__currentPatternLabel.setText( PATTERN_PREAMBLE + self.__loadedPattern.GetName() + ' ' + self.__loadedPattern.GetColorString()) self.__deletePresetPattern() if len(self.__savedPresets) > 0: self.__drawPresetPatternsForSelection() else: self.__drawPatternButtons() else: self.__Log("Unknown button") else: self.__Log("Bad Mode") def __presetPatternSelectedForStart(self, ID): self.__Log("Preset pattern selected with ID %d" % ID) if ID >= 0 and ID < len(self.__savedPresets): self.__selectedPattern = self.__savedPresets[ID] self.__currentPatternLabel.setText( PATTERN_PREAMBLE + self.__selectedPattern.GetName() + ' ' + self.__selectedPattern.GetColorString()) self.__loadedPattern = self.__selectedPattern self.__presetDeleteButton.setEnabled(True) self.StartButton.setEnabled(True) return def __intensitySelected(self, ID): ## NOTE: INtensity does not change until the STOP->START is pressed. self.__Log("Got Intensity: %d" % ID) self.__currentIntensity = ID self.__intensityLabel.setText(INTENSITY_PREAMBLE + str(ID)) self.__mode = self.__lastMode self.__redrawMode() def __colorSelected(self, colorTag): self.__Log("Got Color Selected: %s, setting index %d" % (colorTag, self.__currentColorSelection)) presetColorList = list() if (self.__savedPresets != None): for aPreset in self.__savedPresets: self.__Log("Preset Colors:%s" % (",".join(aPreset.GetColorList()))) newList = list() for color in aPreset.GetColorList(): for presetColor in ColorsByIndex: if presetColor == color: newList += [presetColor] break presetColorList += [newList] self.__Log("Preset Colors:%s" % (",".join(newList))) #presetColorList += [aPreset.GetColorList()] self.__selectedPattern.SetColor(self.__currentColorSelection, colorTag) if self.__savedPresets != None: for ind, aPreset in enumerate(self.__savedPresets): self.__Log("Colors: %s" % (",".join(presetColorList[ind]))) aPreset.SetColorList(presetColorList[ind]) self.__Log("Preset Colors:%s" % (",".join(aPreset.GetColorList()))) ## Check to see if this is now valid if self.__selectedPattern.CanStart(): self.__loadedPattern = self.__selectedPattern self.StartButton.setEnabled(True) self.__drawPatternSettings(self.__selectedPattern) def __savePatternAsPreset(self): self.__Log("Save Pattern As Preset") if self.__selectedPattern.CanStart(): self.__Log("%d Presets already made" % len(self.__savedPresets)) for aPreset in self.__savedPresets: self.__Log("Preset Colors:%s" % (",".join(aPreset.GetColorList()))) if len(self.__savedPresets) < MAX_NUM_PRESETS: # Check to see if there is a duplicate of this already newPattern = Pattern() newPattern.SetName(self.__selectedPattern.GetName()) newPattern.SetDescription( self.__selectedPattern.GetDescription()) newPattern.SetLog(self.__log) newPattern.SetPwmSequenceDict( self.__selectedPattern.GetPwmSequenceDict()) newPattern.SetColorList(self.__selectedPattern.GetColorList()) newPattern.SetRequiredColors( self.__selectedPattern.GetRequiredColors()) self.__Log("Colors %s" % (",".join(newPattern.GetColorList()))) for pattern in self.__savedPresets: if pattern.GetName() == newPattern.GetName(): if pattern.GetColorList() == newPattern.GetColorList(): self.__drawPatternSettings(self.__selectedPattern, False, True, PRESET_EXISTS) return self.__savedPresets += [newPattern] self.__CACHED_PRESET = None self.__Log("Saved Pattern.") self.__presetManager.SavePresetPattern(newPattern) self.__drawPatternSettings(self.__selectedPattern, False, True, PRESET_SAVED) def __patternEditControlPressed(self, buttonTag): if buttonTag == "Back": self.__drawPatternButtons() if self.__loadedPattern != None: self.__currentPatternLabel.setText( PATTERN_PREAMBLE + self.__loadedPattern.GetName() + ' ' + self.__loadedPattern.GetColorString()) else: self.__Log("Unknown tag: %s" % buttonTag) def __patternSelected(self, buttonTag): self.__Log("Pattern \'%s\' pressed" % buttonTag) if buttonTag == PRESET_TAG: self.__Log("Preset Button Pressed.") self.__loadedPatternBeforePreset = self.__loadedPattern self.__drawPresetPatternsForSelection() return # Get the actual pattern from the list of patterns for it in range(0, len(self.__patterns)): self.__selectedPattern = self.__patterns[it] if self.__selectedPattern.GetName() == buttonTag: self.__Log("FOUND PATTERN") self.__selectedPattern.ClearColors() self.__drawPatternSettings(self.__selectedPattern) return self.__Log("Didn't find a pattern that matched tag!") def __handleStart(self): self.__Log("START") if self.__loadedPattern != None: if self.__running: if (self.EXECUTION_THREAD != None): self.EXECUTION_THREAD.join() time.sleep(.5) self.__running = True self.__currentStatusLabel.setText(STATUS_PREAMBLE + RUNNING) self.EXECUTION_THREAD = ExecutionThread(self.__loadedPattern, self.__currentIntensity, self.__log) self.EXECUTION_THREAD.start() time.sleep(.5) def __handleStop(self): self.__Log("STOP") if self.__running: self.__running = False #self.__selectedPattern.ClearColors() #self.__currentPatternLabel.setText(PATTERN_PREAMBLE + NO_PATTERN_SELECTED) self.__currentStatusLabel.setText(STATUS_PREAMBLE + STOPPED) # Stop Threading if (self.EXECUTION_THREAD != None): self.EXECUTION_THREAD.join() time.sleep(.5) self.__redrawMode() def __phoneHome(self): if RASPI: os.system("/home/pi/Desktop/Lightbox/util/phoneHome.sh &") def __exit(self): self.__handleStop() self.close() def __shutdown(self): response = QMessageBox.question(self, "Shutdown", "Proceed with shutdown?", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if response == QMessageBox.Yes: self.__handleStop() if RASPI: os.system("sudo shutdown -h 0") self.close() ### DISABLED----------------------------------------------------- def __addPattern(self): self.__Log("Add Pattern") newPattern = Pattern() newDescription = "Pattern %d" % (len(self.__patterns)) self.__Log("New description %s" % newDescription) copyPattern = self.__patterns[0] newPattern = copyPattern.CopyPattern(newDescription) self.__patterns += [newPattern] self.__drawPatternButtons() ## Delete a preset pattern -------------------------------------- def __deletePresetPattern(self): self.__Log("Delete Preset Pattern") self.__savedPresets.remove(self.__presetPatternForDeleting) self.__presetManager.DeletePresetPattern( self.__presetPatternForDeleting) def __setFont(self, object, size): font = QFont(object.font()) font.setPointSize(size) object.setFont(font) def __startValid(self): self.__Log("In start Valid") if self.__mode == PATTERN_EDIT_MODE or self.__mode == PATTERN_PRESET_SELECT_MODE: if self.__selectedPattern != None: self.StartButton.setEnabled(self.__selectedPattern.CanStart()) else: self.StartButton.setEnabled(False) self.__Log( "In edit mode/preset selection (same state as edit, selectedPattern has to be valid." ) elif self.__loadedPattern != None: self.__Log("Looking at loaded pattern") if self.__loadedPattern.CanStart(): self.StartButton.setEnabled(self.__loadedPattern.CanStart()) else: self.StartButton.setEnabled(False) def __redrawMode(self): if self.__mode == PATTERN_EDIT_MODE: self.__drawPatternSettings(self.__selectedPattern) elif self.__mode == PATTERN_SELECT_MODE: self.__drawPatternButtons() elif self.__mode == PATTERN_PRESET_SELECT_MODE: self.__drawPresetPatternsForSelection() elif self.__mode == INTENSITY_SELECT_MODE: if (self.__modeBeforeIntensity != None): if self.__modeBeforeIntensity == PATTERN_EDIT_MODE: self.__drawPatternSettings(self.__selectedPattern) elif self.__mode == PATTERN_SELECT_MODE: self.__drawPatternButtons() elif self.__mode == PATTERN_PRESET_SELECT_MODE: self.__drawPresetPatternsForSelection() else: self.__drawPatternButtons() else: self.__drawPatternButtons() else: self.__Log("No mode to redraw") ## Draw the Premade pattern buttons ------------------------------------------------ def __drawPatternButtons(self): self.__mode = PATTERN_SELECT_MODE self.__startValid() self.__clearLayout(self.__selectedPatternLayout) self.__clearLayout(self.__defaultButtonLayout) self.__clearLayout(self.__intensitySelectLayout) self.__clearLayout(self.__presetButtonLayout) self.__defaultButtonLayout = QVBoxLayout() self.__selectedPatternLayout = QVBoxLayout() self.__intensityLayout = QVBoxLayout() self.__presetButtonLayout = QVBoxLayout() self.__buttons = list() # add label for this screen patternLabelLayout = QHBoxLayout() patternLabelLayout.addStretch(1) patternLabel = QLabel("Temporal Patterns") self.__setFont(patternLabel, PAGE_INFO_LABEL_SIZE) patternLabelLayout.addWidget(patternLabel) patternLabelLayout.addStretch(1) self.__defaultButtonLayout.addLayout(patternLabelLayout) self.__Log("Redrawing Buttons") numOfButtons = len(self.__patterns) # + 1 # One for preset numOfRows = numOfButtons / BUTTONS_PER_ROW lastRowStretch = False if numOfButtons % BUTTONS_PER_ROW != 0: numOfRows += 1 lastRowStretch = True self.__Log("Buttons: %d, Rows: %d" % (numOfButtons, numOfRows)) for i in range(0, numOfRows): #self.__Log("Row %d"%i) newRow = QHBoxLayout() buttonsLeft = numOfButtons - i * BUTTONS_PER_ROW buttonsInRow = BUTTONS_PER_ROW if buttonsLeft < BUTTONS_PER_ROW: buttonsInRow = buttonsLeft newRow.addStretch(1) for j in range(0, buttonsInRow): patternId = i * BUTTONS_PER_ROW + j #print "Pattern ID %d"%patternId pattern = self.__patterns[patternId] name = pattern.GetName() desc = pattern.GetDescription() #print "Name %s"%name newLabel = QLabel(desc) self.__setFont(newLabel, PATTERN_LABEL_FONT_SIZE) newButton = TagPushButton(self, name) newButton.setMinimumSize(MIN_BUTTON_WIDTH, MIN_BUTTON_HEIGHT) self.__setFont(newButton, PATTERN_BUTTON_FONT_SIZE) self.__buttons.append(newButton) newButtonLayout = QVBoxLayout() newButtonLayout.addWidget(newButton) labelLayout = QHBoxLayout() labelLayout.addStretch() labelLayout.addWidget(newLabel) labelLayout.addStretch() newButtonLayout.addLayout(labelLayout) newButtonLayout.addStretch(1) newRow.addLayout(newButtonLayout) # Iflast row and < full, add stretch to left and right side (left done above) if lastRowStretch and i == numOfRows - 1: ## Add the preset button here, we know it's there button = TagPushButton(self, PRESET_TAG) self.__setFont(button, PATTERN_BUTTON_FONT_SIZE) button.setMinimumSize(MIN_BUTTON_WIDTH, MIN_BUTTON_HEIGHT) presetLayout = QVBoxLayout() presetLayout.addWidget(button) presetLayout.addStretch(1) newRow.addLayout(presetLayout) newRow.addStretch(1) self.__defaultButtonLayout.addLayout(newRow) self.__mainLayout.addLayout(self.__defaultButtonLayout) ## Draw Settings Window ------------------------------------------------------- def __drawPatternSettings(self, pattern, withColors=False, withLogMessage=False, logMessage=""): self.__mode = PATTERN_EDIT_MODE if pattern.CanStart(): self.__currentPatternLabel.setText(PATTERN_PREAMBLE + pattern.GetName() + ' ' + pattern.GetColorString()) else: self.__currentPatternLabel.setText(PATTERN_PREAMBLE + EMPTY_PATTERN_SELECTED) self.__startValid() self.__Log("Draw pattern settings") self.__Log("Pattern \'%s\' pressed" % pattern.GetName()) self.__Log("Clearing pattern layout.") self.__clearLayout(self.__selectedPatternLayout) self.__clearLayout(self.__defaultButtonLayout) self.__clearLayout(self.__intensitySelectLayout) self.__clearLayout(self.__presetButtonLayout) self.__defaultButtonLayout = QVBoxLayout() self.__selectedPatternLayout = QVBoxLayout() self.__intensityLayout = QVBoxLayout() self.__presetButtonLayout = QVBoxLayout() # Pattern picture patternLayout = QHBoxLayout() patLabel = QLabel(pattern.GetName()) self.__setFont(patLabel, PAGE_INFO_LABEL_SIZE) image = QLabel("ICON HERE") patternLayout.addStretch(1) patternLayout.addWidget(patLabel) patternLayout.addStretch(1) self.__selectedPatternLayout.addLayout(patternLayout) # Color choosing buttons numOfColors = pattern.GetRequiredColors() self.__Log("Number of required colors is %d" % numOfColors) colorButtonLayout = QHBoxLayout() colorButtonLayout.addStretch(1) for x in range(1, numOfColors + 1, 1): buttonLayout = QVBoxLayout() # Make Button newButton = IDPushButton(self, "Color %d..." % x, x) self.__setFont(newButton, PATTERN_BUTTON_FONT_SIZE) newButton.setMaximumSize(100, 100) # Make Label newLabel = QLabel(self.__selectedPattern.GetColorByIndex(x - 1)) self.__setFont(newLabel, PATTERN_LABEL_FONT_SIZE) buttonLayout.addWidget(newButton) labelLayout = QHBoxLayout() labelLayout.addStretch(1) labelLayout.addWidget(newLabel) labelLayout.addStretch(1) # Add label to button layout, button layout to color button layout buttonLayout.addLayout(labelLayout) colorButtonLayout.addLayout(buttonLayout) colorButtonLayout.addStretch(1) self.__selectedPatternLayout.addLayout(colorButtonLayout) if withColors: self.__selectedPatternLayout.addLayout( self.__colorButtonChooserLayout) self.__selectedPatternLayout.addStretch(1) # Control buttons controlButtonLayout = QHBoxLayout() controlButtonLayout.addStretch(1) saveButton = TagPushButton(self, "Save as Preset") saveIcon = QIcon(SAVE_ICON_LOC) saveButton.setIcon(saveIcon) backButton = TagPushButton(self, "Back") backIcon = QIcon(BACK_ICON_LOC) backButton.setIcon(backIcon) saveButton.setMinimumSize(CONTROL_BUTTON_WIDTH, CONTROL_BUTTON_HEIGHT) backButton.setMinimumSize(CONTROL_BUTTON_WIDTH, CONTROL_BUTTON_HEIGHT) self.__setFont(saveButton, CONTROL_BUTTON_FONT_SIZE) self.__setFont(backButton, CONTROL_BUTTON_FONT_SIZE) ## If we just saved a preset, show the QLabel that we did. if (withLogMessage and logMessage != ""): logLabel = QLabel(logMessage) self.__setFont(logLabel, CONTROL_LABEL_FONT_SIZE) controlButtonLayout.addWidget(logLabel) ## Check to see if adding a preset is okay? if len(self.__savedPresets) >= MAX_NUM_PRESETS: saveButton.setEnabled(False) presetsFullLabel = QLabel("Presets Full!") self.__setFont(presetsFullLabel, CONTROL_LABEL_FONT_SIZE) controlButtonLayout.addWidget(presetsFullLabel) else: saveButton.setEnabled(self.__selectedPattern.CanStart()) controlButtonLayout.addWidget(saveButton) controlButtonLayout.addWidget(backButton) self.__selectedPatternLayout.addLayout(controlButtonLayout) self.__mainLayout.addLayout(self.__selectedPatternLayout) def __drawColorButtons(self): self.__colorButtonChooserLayout = QHBoxLayout() numOfColors = len(Colors) for i in range(0, numOfColors - 1): ## -1 excludes the Empty button = TagPushButton(self, Colors[i]) self.__setFont(button, PATTERN_BUTTON_FONT_SIZE) button.setIcon(self.ColorIcons[i]) self.__colorButtonChooserLayout.addWidget(button) self.__drawPatternSettings(self.__selectedPattern, True) def __drawIntensityButtons(self): self.__modeBeforeIntensity = self.__mode self.__mode = INTENSITY_SELECT_MODE self.__Log("Draw intensity buttons") self.__clearLayout(self.__selectedPatternLayout) self.__clearLayout(self.__defaultButtonLayout) self.__clearLayout(self.__intensitySelectLayout) self.__clearLayout(self.__presetButtonLayout) self.__defaultButtonLayout = QVBoxLayout() self.__selectedPatternLayout = QVBoxLayout() self.__intensitySelectLayout = QVBoxLayout() self.__presetButtonLayout = QVBoxLayout() self.__intensitySelectLayout.addStretch(1) labelLayout = QHBoxLayout() labelLayout.addStretch(1) intensityLabel = QLabel("Intensity Select (candela)") self.__setFont(intensityLabel, PAGE_INFO_LABEL_SIZE) labelLayout.addWidget(intensityLabel) labelLayout.addStretch(1) self.__intensitySelectLayout.addLayout(labelLayout) numOfButtons = len(Intensities) maxButtonsPerRow = 3 numOfRows = numOfButtons / maxButtonsPerRow if numOfButtons % maxButtonsPerRow != 0: numOfRows += 1 for i in range(0, numOfRows): rowLayout = QHBoxLayout() rowLayout.addStretch(1) buttonsLeft = numOfButtons - i * maxButtonsPerRow buttonsInRow = maxButtonsPerRow if buttonsLeft < maxButtonsPerRow: buttonsInRow = buttonsLeft for j in range(0, buttonsInRow): button = IDPushButton( self, str(Intensities[j + (i * maxButtonsPerRow)]), Intensities[j + (i * maxButtonsPerRow)]) self.__setFont(button, INTENSITY_BUTTON_FONT_SIZE) button.setMinimumSize(INTENSITY_BUTTON_MIN_WIDTH, INTENSITY_BUTTON_MIN_HEIGHT) rowLayout.addWidget(button) rowLayout.addStretch(1) self.__intensitySelectLayout.addLayout(rowLayout) self.__mainLayout.addLayout(self.__intensitySelectLayout) def __drawPresetPatternsForSelection(self): if len(self.__savedPresets) > 0: self.__mode = PATTERN_PRESET_SELECT_MODE self.__createPresetPatternLayout() controlLayout = QHBoxLayout() controlLayout.addStretch(1) self.__presetDeleteButton = TagPushButton(self, "Delete") deleteIcon = QIcon(DELETE_ICON_LOC) self.__presetDeleteButton.setIcon(deleteIcon) self.__setFont(self.__presetDeleteButton, CONTROL_BUTTON_FONT_SIZE) self.__presetDeleteButton.setMinimumSize(CONTROL_BUTTON_WIDTH, CONTROL_BUTTON_HEIGHT) self.__presetDeleteButton.setEnabled(False) backButton = TagPushButton(self, "Back") self.__setFont(backButton, CONTROL_BUTTON_FONT_SIZE) backButton.setMinimumSize(CONTROL_BUTTON_WIDTH, CONTROL_BUTTON_HEIGHT) backIcon = QIcon(BACK_ICON_LOC) backButton.setIcon(backIcon) controlLayout.addWidget(self.__presetDeleteButton) controlLayout.addWidget(backButton) self.__presetButtonLayout.addStretch(1) self.__presetButtonLayout.addLayout(controlLayout) self.__mainLayout.addLayout(self.__presetButtonLayout) self.__selectedPattern = None self.__startValid() def __createPresetPatternLayout(self): self.__clearLayout(self.__selectedPatternLayout) self.__clearLayout(self.__defaultButtonLayout) self.__clearLayout(self.__intensitySelectLayout) self.__clearLayout(self.__presetButtonLayout) self.__currentPatternLabel.setText(PATTERN_PREAMBLE + EMPTY_PATTERN_SELECTED) self.__defaultButtonLayout = QVBoxLayout() self.__selectedPatternLayout = QVBoxLayout() self.__intensityLayout = QVBoxLayout() self.__presetButtonLayout = QVBoxLayout() presetLabelLayout = QHBoxLayout() presetLabelLayout.addStretch(1) presetPatternLabel = QLabel("Preset Patterns") self.__setFont(presetPatternLabel, PAGE_INFO_LABEL_SIZE) presetLabelLayout.addWidget(presetPatternLabel) presetLabelLayout.addStretch(1) self.__presetButtonLayout.addLayout(presetLabelLayout) if len(self.__savedPresets) <= 0: return numOfButtons = len(self.__savedPresets) numOfRows = numOfButtons / BUTTONS_PER_ROW lastRowStretch = False if numOfButtons % BUTTONS_PER_ROW != 0: numOfRows += 1 lastRowStretch = True self.__Log("Buttons: %d, Rows: %d" % (numOfButtons, numOfRows)) for i in range(0, numOfRows): self.__Log("Row %d" % i) newRow = QHBoxLayout() buttonsLeft = numOfButtons - i * BUTTONS_PER_ROW buttonsInRow = BUTTONS_PER_ROW if buttonsLeft < BUTTONS_PER_ROW: buttonsInRow = buttonsLeft newRow.addStretch(1) for j in range(0, buttonsInRow): patternId = i * BUTTONS_PER_ROW + j #print "Pattern ID %d"%patternId pattern = self.__savedPresets[patternId] name = pattern.GetName() desc = ",".join(pattern.GetColorList()) #print "Name %s"%name newLabel = QLabel(desc) self.__setFont(newLabel, PATTERN_LABEL_FONT_SIZE) newButton = IDPushButton(self, name, patternId) newButton.setMinimumSize(MIN_BUTTON_WIDTH, MIN_BUTTON_HEIGHT) self.__setFont(newButton, PATTERN_BUTTON_FONT_SIZE) self.__buttons.append(newButton) newButtonLayout = QVBoxLayout() newButtonLayout.addWidget(newButton) labelLayout = QHBoxLayout() labelLayout.addStretch(1) labelLayout.addWidget(newLabel) labelLayout.addStretch(1) newButtonLayout.addLayout(labelLayout) newRow.addLayout(newButtonLayout) # Iflast row and < full, add stretch to left and right side (left done above) if lastRowStretch and i == numOfRows - 1: newRow.addStretch(1) self.__presetButtonLayout.addLayout(newRow)
class EditNodeProperties(QDialog): def __init__(self, data, win_parent=None): """ +-----------------+ | Edit Node Props | +-----------------+------+ | LEwingTip | | Node2 | | Node3 | | Node4 | | | | All Nodes: | | Color red | | PointSize 3 | | Opacity 0.3 | | Show/Hide | | | | Name LEwingTip | | Location X Y Z | | Coord 0 | | CoordType R, C, S | | | | Previous Next | | | | Close | +------------------------+ """ QDialog.__init__(self, win_parent) self.setWindowTitle('Edit Node Properties') #default self.win_parent = win_parent self.out_data = data point_properties = data['point_properties'] print(point_properties) #name = point_properties.name point_size = point_properties.point_size opacity = point_properties.opacity color = point_properties.color show = point_properties.is_visible self.points = data['points'] self.keys = sorted(self.points.keys()) keys = self.keys #nrows = len(keys) active_point = data['active_point'] #self.active_key = keys[0] self.active_key = active_point name = self.active_key description = self.points[self.active_key][0] self._use_old_table = False items = ['Node %i' % val for val in keys] header_labels = ['Nodes'] table_model = Model(items, header_labels, self) view = SingleChoiceQTableView(self) #Call your custom QTableView here view.setModel(table_model) if qt_version in [4, 'pyside']: view.horizontalHeader().setResizeMode(QHeaderView.Stretch) else: view.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) self.table = view #self.representation = actor_obj.representation #print('rep =', self.representation) table = self.table #headers = [QtCore.QString('Groups')] header = table.horizontalHeader() header.setStretchLastSection(True) #---------------------------------------------- #self._default_is_apply = False self.color = QLabel("Color:") self.color_edit = QPushButton() #self.color_edit.setFlat(True) color = self.out_data['point_properties'].color opacity = self.out_data['point_properties'].opacity show = self.out_data['point_properties'].is_visible #color = self.out_data[self.active_key].color qcolor = QColor() qcolor.setRgb(*color) #print('color =%s' % str(color)) palette = QPalette( self.color_edit.palette()) # make a copy of the palette #palette.setColor(QPalette.Active, QPalette.Base, \ #qcolor) palette.setColor(QPalette.Background, QColor('blue')) # ButtonText self.color_edit.setPalette(palette) self.color_edit.setStyleSheet("QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(color) + #"border:1px solid rgb(255, 170, 255); " "}") self.all_nodes_header = QLabel("All Nodes:") self.point_size = QLabel("Point Size:") self.point_size_edit = QSpinBox(self) self.point_size_edit.setRange(1, 10) self.point_size_edit.setSingleStep(1) self.point_size_edit.setValue(point_size) self.opacity = QLabel("Opacity:") self.opacity_edit = QDoubleSpinBox(self) self.opacity_edit.setRange(0.1, 1.0) self.opacity_edit.setDecimals(1) self.opacity_edit.setSingleStep(0.1) self.opacity_edit.setValue(opacity) # show/hide self.checkbox_show = QCheckBox("Show") self.checkbox_hide = QCheckBox("Hide") self.checkbox_show.setChecked(show) self.checkbox_hide.setChecked(not show) #---------------------------------------------- self.nodes_header = QLabel("Single Node:") self.name = QLabel("ID:") self.name_edit = QLineEdit('Node %i' % name) self.name_edit.setDisabled(True) self.description = QLabel("Description:") self.description_edit = QLineEdit(str(description)) #self.description_edit.setDisabled(True) location_x = 0.1 location_y = 0.1 location_z = 0.1 self.location = QLabel("Location:") self.location_x_edit = QDoubleSpinBox(self) self.location_y_edit = QDoubleSpinBox(self) self.location_z_edit = QDoubleSpinBox(self) #self.location_x_edit.setDecimals(1) delta_x = abs(location_x) / 100. if location_x != 0.0 else 0.1 delta_y = abs(location_y) / 100. if location_y != 0.0 else 0.1 delta_z = abs(location_z) / 100. if location_z != 0.0 else 0.1 self.location_x_edit.setSingleStep(delta_x) self.location_y_edit.setSingleStep(delta_y) self.location_z_edit.setSingleStep(delta_z) self.location_x_edit.setValue(location_x) self.location_y_edit.setValue(location_y) self.location_z_edit.setValue(location_z) self.coord = QLabel("Coord:") self.coord_edit = QSpinBox(self) self.coord_edit.setRange(0, 99999999) #self.coord_edit.setSingleStep(1) self.coord_edit.setValue(0) self.coord_type = QLabel("Coord Type:") #---------------------------------------------- # closing #if self._default_is_apply: #self.apply_button.setDisabled(True) self.close_button = QPushButton("Close") self.create_layout() self.set_connections() def update_active_key(self, index): name = self.active_key old_obj = self.out_data['points'][name] #self.active_key #self.points[self.active_key] old_obj[0] = str(self.description_edit.text()) #old_obj.coord = self.description_edit.value() #old_obj.description = self.description_edit.value() #old_obj.description = self.description_edit.value() str_name = str(index.data().toString()) name = int(str_name[5:]) #i = self.keys.index(self.active_key) self.active_key = name point = self.points[self.active_key] #1 : ['LERoot', 0, 'R', 1.0, 2.0, 3.0], self.name_edit.setText(str(self.active_key)) self.description_edit.setText(point[0]) self.coord_edit.setValue(point[1]) if point[2] == 'R': self.radio_rectangular.setChecked(True) elif point[2] == 'C': self.radio_cylindrical.setChecked(True) elif point[2] == 'S': self.radio_spherical.setChecked(True) self.location_x_edit.setValue(point[3]) self.location_y_edit.setValue(point[4]) self.location_z_edit.setValue(point[5]) #obj = self.out_data[name] #point_size = obj.point_size #opacity = obj.opacity #representation = obj.representation #is_visible = obj.is_visible #self.opacity_edit.setValue(opacity) #self.checkbox_show.setChecked(is_visible) #self.checkbox_hide.setChecked(not is_visible) #def on_name_select(self): #print('on_name_select') #return def create_layout(self): cancel_box = QHBoxLayout() cancel_box.addWidget(self.close_button) grid1 = QGridLayout() grid2 = QGridLayout() #----------------------------------------- # setup self.radio_rectangular = QRadioButton('Rectangular') self.radio_cylindrical = QRadioButton('Cylindrical') self.radio_spherical = QRadioButton('Spherical') coord_type_layout = QHBoxLayout() coord_type_layout.addWidget(self.radio_rectangular) coord_type_layout.addWidget(self.radio_cylindrical) coord_type_layout.addWidget(self.radio_spherical) location_layout = QHBoxLayout() location_layout.addWidget(self.location_x_edit) location_layout.addWidget(self.location_y_edit) location_layout.addWidget(self.location_z_edit) checkboxs = QButtonGroup(self) checkboxs.addButton(self.checkbox_show) checkboxs.addButton(self.checkbox_hide) vbox1 = QVBoxLayout() vbox1.addWidget(self.checkbox_show) vbox1.addWidget(self.checkbox_hide) #vbox1.addLayout(checkboxs) #----------------------------------------- irow = 0 grid1.addWidget(self.all_nodes_header, irow, 0) irow += 1 grid1.addWidget(self.color, irow, 0) grid1.addWidget(self.color_edit, irow, 1) irow += 1 grid1.addWidget(self.opacity, irow, 0) grid1.addWidget(self.opacity_edit, irow, 1) irow += 1 grid1.addWidget(self.point_size, irow, 0) grid1.addWidget(self.point_size_edit, irow, 1) irow += 1 #----------------------------------------- irow = 0 grid2.addWidget(self.nodes_header, irow, 0) irow += 1 grid2.addWidget(self.name, irow, 0) grid2.addWidget(self.name_edit, irow, 1) irow += 1 grid2.addWidget(self.description, irow, 0) grid2.addWidget(self.description_edit, irow, 1) irow += 1 #| All Nodes: | #| Color red | #| PointSize 3 | #| Opacity 0.3 | #| Show/Hide | #| | #| Name LEwingTip | #| Location X Y Z | #| Coord 0 | #| CoordType R, C, S | #| | #| Previous Next | grid2.addWidget(self.coord, irow, 0) grid2.addWidget(self.coord_edit, irow, 1) irow += 1 grid2.addWidget(self.coord_type, irow, 0) grid2.addLayout(coord_type_layout, irow, 1) irow += 1 grid2.addWidget(self.location, irow, 0) grid2.addLayout(location_layout, irow, 1) irow += 1 #------------------------------------ vbox = QVBoxLayout() vbox.addLayout(grid1) vbox.addLayout(vbox1) vbox.addStretch() vbox.addWidget(self.table) vbox.addLayout(grid2) vbox.addStretch() #vbox.addWidget(self.check_apply) vbox.addLayout(cancel_box) self.setLayout(vbox) def set_connections(self): if qt_version == 4: self.connect(self.opacity_edit, QtCore.SIGNAL('clicked()'), self.on_opacity) self.connect(self.point_size, QtCore.SIGNAL('clicked()'), self.on_point_size) self.connect(self.color_edit, QtCore.SIGNAL('clicked()'), self.on_color) self.connect(self.checkbox_show, QtCore.SIGNAL('clicked()'), self.on_show) self.connect(self.checkbox_hide, QtCore.SIGNAL('clicked()'), self.on_hide) self.connect(self.description_edit, QtCore.SIGNAL("valueChanged(int)"), self.on_description) self.connect(self.coord_edit, QtCore.SIGNAL("valueChanged(int)"), self.on_coord) self.connect(self.radio_rectangular, QtCore.SIGNAL('clicked()'), self.on_coord_type) self.connect(self.radio_cylindrical, QtCore.SIGNAL('clicked()'), self.on_coord_type) self.connect(self.radio_spherical, QtCore.SIGNAL('clicked()'), self.on_coord_type) self.connect(self.location_x_edit, QtCore.SIGNAL('clicked()'), self.on_location_x) self.connect(self.location_y_edit, QtCore.SIGNAL('clicked()'), self.on_location_y) self.connect(self.location_z_edit, QtCore.SIGNAL('clicked()'), self.on_location_z) self.connect(self.close_button, QtCore.SIGNAL('clicked()'), self.on_close) #self.connect(self.check_apply, QtCore.SIGNAL('clicked()'), self.on_check_apply) #self.connect(self.apply_button, QtCore.SIGNAL('clicked()'), self.on_apply) #self.connect(self.ok_button, QtCore.SIGNAL('clicked()'), self.on_ok) #self.connect(self.close_button, QtCore.SIGNAL('clicked()'), self.on_close) else: pass #self.opacity_edit.clicked.connect(self.on_opacity) #self.point_size.clicked.connect(self.on_point_size) #self.color_edit.clicked.connect(self.on_color) #self.checkbox_show.clicked.connect(self.on_show) #self.checkbox_hide.clicked.connect(self.on_hide) #self.description_edit.valueChanged.connect(self.on_description) #self.coord_edit.valueChanged.connect(self.on_coord) #self.radio_rectangular.clicked.connect(self.on_coord_type) #self.radio_cylindrical.clicked.connect(self.on_coord_type) #self.radio_spherical.clicked.connect(self.on_coord_type) #self.location_x_edit.clicked.connect(self.on_location_x) #self.location_y_edit.clicked.connect(self.on_location_y) #self.location_z_edit.clicked.connect(self.on_location_z) self.close_button.clicked.connect(self.on_close) def on_color(self): obj = self.out_data['point_properties'] rgb_color_ints = obj.color msg = 'Points' col = QColorDialog.getColor(QColor(*rgb_color_ints), self, "Choose a %s color" % msg) if col.isValid(): color = col.getRgbF()[:3] obj.color = color #print('new_color =', color) self.color_edit.setStyleSheet( "QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(obj.color) + #"border:1px solid rgb(255, 170, 255); " "}") def on_show(self): is_checked = self.checkbox_show.isChecked() self.out_data['point_properties'].is_visible = is_checked def on_hide(self): is_checked = self.checkbox_hide.isChecked() self.out_data['point_properties'].is_visible = not is_checked def on_point_size(self): point_size = self.point_size_edit.value() self.out_data['point_properties'].point_size = point_size def on_opacity(self): opacity = self.opacity_edit.value() self.out_data['point_properties'].opacity = opacity def on_description(self): #1 : ['LERoot', 0, 'R', 1.0, 2.0, 3.0], name = self.active_key description = self.description_edit.value() self.out_data['points'][name][0] = description def on_coord(self): #1 : ['LERoot', 0, 'R', 1.0, 2.0, 3.0], name = self.active_key coord_id = self.coord_edit.value() self.out_data['points'][name][1] = coord_id def on_coord_type(self): #1 : ['LERoot', 0, 'R', 1.0, 2.0, 3.0], name = self.active_key if self.radio_rectangular.isChecked(): coord_type = 'R' elif self.radio_cylindrical.isChecked(): coord_type = 'C' elif self.radio_spherical.isChecked(): coord_type = 'S' else: raise NotImplementedError() self.out_data['points'][name][2] = coord_type def on_location_x(self): #1 : ['LERoot', 0, 'R', 1.0, 2.0, 3.0], name = self.active_key value = self.coord_edit.value() self.out_data['points'][name][3] = value def on_location_y(self): #1 : ['LERoot', 0, 'R', 1.0, 2.0, 3.0], name = self.active_key value = self.coord_edit.value() self.out_data['points'][name][4] = value def on_location_z(self): #1 : ['LERoot', 0, 'R', 1.0, 2.0, 3.0], name = self.active_key value = self.coord_edit.value() self.out_data['points'][name][5] = value def closeEvent(self, event): event.accept() #def on_default_name(self): #self.name_edit.setText(str(self._default_name)) #self.name_edit.setStyleSheet("QLineEdit{background: white;}") #def check_float(self, cell): #text = cell.text() #try: #value = eval_float_from_string(text) #cell.setStyleSheet("QLineEdit{background: white;}") #return value, True #except ValueError: #cell.setStyleSheet("QLineEdit{background: red;}") #return None, False #def check_name(self, cell): #text = str(cell.text()).strip() #if len(text): #cell.setStyleSheet("QLineEdit{background: white;}") #return text, True #else: #cell.setStyleSheet("QLineEdit{background: red;}") #return None, False def on_validate(self): self.out_data['clicked_ok'] = True self.out_data['clicked_cancel'] = False old_obj = self.out_data[self.active_key] old_obj.point_size = self.point_size_edit.value() old_obj.opacity = self.opacity_edit.value() old_obj.is_visible = self.checkbox_show.isChecked() return True #name_value, flag0 = self.check_name(self.name_edit) #ox_value, flag1 = self.check_float(self.transparency_edit) #if flag0 and flag1: #self.out_data['clicked_ok'] = True #return True #return False def on_apply(self): passed = self.on_validate() if passed: self.win_parent.on_update_gui_nodes(self.out_data) return passed def on_ok(self): passed = self.on_apply() if passed: self.close() #self.destroy() def on_close(self): self.out_data['clicked_close'] = True self.close()
class QProcessControl(QWidget): def __new__(cls, command): # Check if the command dictionary has the required size if len(command) != 4: print('Error: Incorrect argument passed to constructor. Expecting dictionary format:\n' + '{\n\t"command"\t: "<roslaunch|rosrun>",' + '\n\t"pkg"\t\t: "<pkg_name>",' + '\n\t"node"\t\t: "<nodeFile|[launchFile(s)]>"' + '\n\t"pid"\t\t: "<pid_fila_path>' + '\n}') return None print 'List found' # Check if all required keys are present in the command dictionary for key in ['command', 'pkg', 'node', 'pid']: if key not in command: return None print 'Integrity check for list passed' # Check if the "command" is a known one if command['command'] not in ['roslaunch', 'rosrun']: print 'Error: Unknown command. Choose between "roslaunch" and "rosrun"' return None print 'Correct command' # If "roslaunch" was selected as "command", check if "node" contains a list of one or more values (the roslaunch command can start multiple launch files at once) if command['command'] == 'roslaunch' and not isinstance(command['node'], list): print 'Error: Expecting list of one or more launch files in "node"' return None print 'Correct command parameters' return super(QProcessControl, cls).__new__(cls) def __init__(self, command): super(QProcessControl, self).__init__() print 'Init' self.command = command self.args = [command['pkg']] # In case we have a roslaunch command we extract all launch files from "node" and append them as command's arguments if command['command'] == 'roslaunch': for launchFile in command['node']: self.args.append(launchFile) else: # Else we have a rosrun and we can have only a single node we can run so we append directly "node" self.args.append(command['node']) self.status = False self.pid = 0 # self.pidFilePath = 'qpc.pid' self.pidFilePath = command['pid'] if os.path.isfile(self.pidFilePath): print 'Found \"' + self.pidFilePath + '\". Restoring connection to detached process' with open(self.pidFilePath) as f: self.pid = int(f.readline()) # TODO: this has to be long but damn it's so hard to parse long values in Python O_O print 'PID: ', self.pid self.status = True else: print 'Warning: No \"' + self.pidFilePath + '\" detected. If you have started the detached process, closed the UI and deleted this file, the application will be unable to restore its state and the external process will be orphaned!' self.initUI() def initUI(self): self.hbox = QHBoxLayout() self.qbtn = QPushButton('Start', self) self.qbtn.setCheckable(True) if self.status: self.qbtn.setChecked(True) self.qbtn.setText('Stop') self.qbtn.clicked.connect(self.toggleProcess) self.qbtn.resize(self.qbtn.sizeHint()) self.hbox.addWidget(self.qbtn) self.setLayout(self.hbox) self.setGeometry(300, 300, 250, 150) self.setWindowTitle('QProcess controlled by a button') self.show() def toggleProcess(self, val): if val: print 'Starting process' # Note: when roslaunch is terminated all processes spawned by it are also terminated # thus even if roscore has been started by the roslaunch process it will too be stopped :) # self.status, self.pid = QProcess.startDetached('roslaunch', ['lt', 'talker.launch'], '.') #(self.command, self.args, '.') self.status, self.pid = QProcess.startDetached(self.command['command'], self.args, '.') #(self.command, self.args, '.') if self.status: print 'PID: ', self.pid pidFile = open(self.pidFilePath, 'w') pidFile.write(str(self.pid)) pidFile.close() self.qbtn.setText('Stop') else: self.qbtn.setChecked(False) print 'Error: Failed to create process!' else: print 'Stopping process' if self.status: # kill takes a very short amount of time hence we can call it from inside the main thread without freezing the UI self.success = None if self.command['command'] == 'rosnode': self.success = subprocess.call(['rosnode', 'kill', 'talker']) else: if check_pid(self.pid): self.success = os.kill(self.pid, SIGINT) else: print 'Error: No process with PID ' + str(self.pid) + ' detected' if os.path.isfile(self.pidFilePath): os.remove(self.pidFilePath) # self.qbtn.setChecked(True) # NOTE: using scripts (rosrun pkg_name script.py) and not launching ROS-confrom nodes creates # nodes like "talker_121314_12121414", which are impossible to distinguish without too much # fuss and make it really difficult to use 'rosnode kill' hence the requirement to start only # nodes that have a simple, distinguishable name so that rosnode kill can be used or use roslaunch # and launch files to give proper names # == 0 : for subprocess.call() return value | == None : for os.kill() return value (None -> kill was successful) if self.success == 0 or self.success == None: print 'Process stopped!' self.status = False self.pid = 0 if os.path.isfile(self.pidFilePath): os.remove(self.pidFilePath) self.qbtn.setText('Start') else: print 'Error: Failed to stop process!' self.qbtn.setChecked(True)
class __MiscContainer(QWidget): """From Miscellaneous, contains all the widgets in the bottom area.""" #Miscellaneous was to long and dificult to write :P def __init__(self, parent=None): QWidget.__init__(self, parent) vbox = QVBoxLayout(self) vbox.setContentsMargins(0, 0, 0, 0) vbox.setSpacing(0) self.__toolbar = QToolBar() self.__toolbar.setObjectName('custom') hbox = QHBoxLayout() vbox.addLayout(hbox) self.stack = StackedWidget() vbox.addWidget(self.stack) self._console = console_widget.ConsoleWidget() self.stack.addWidget(self._console) self._runWidget = run_widget.RunWidget() self.stack.addWidget(self._runWidget) self._web = web_render.WebRender() self.stack.addWidget(self._web) self._findInFilesWidget = find_in_files.FindInFilesWidget( self.parent()) self.stack.addWidget(self._findInFilesWidget) #Last Element in the Stacked widget self._results = results.Results(self) self.stack.addWidget(self._results) self._btnConsole = QPushButton(QIcon(resources.IMAGES['console']), '') self._btnConsole.setToolTip(self.tr("Console")) self._btnRun = QPushButton(QIcon(resources.IMAGES['play']), '') self._btnRun.setToolTip(self.tr("Output")) self._btnWeb = QPushButton(QIcon(resources.IMAGES['web']), '') self._btnWeb.setToolTip(self.tr("Web Preview")) self._btnFind = QPushButton(QIcon(resources.IMAGES['find']), '') self._btnFind.setToolTip(self.tr("Find in Files")) #Toolbar hbox.addWidget(self.__toolbar) self.__toolbar.addWidget(self._btnConsole) self.__toolbar.addWidget(self._btnRun) self.__toolbar.addWidget(self._btnWeb) self.__toolbar.addWidget(self._btnFind) self.__toolbar.addSeparator() hbox.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding)) btn_close = QPushButton( self.style().standardIcon(QStyle.SP_DialogCloseButton), '') btn_close.setObjectName('navigation_button') btn_close.setToolTip(self.tr('F4: Show/Hide')) hbox.addWidget(btn_close) self.connect(self._btnConsole, SIGNAL("clicked()"), lambda: self._item_changed(0)) self.connect(self._btnRun, SIGNAL("clicked()"), lambda: self._item_changed(1)) self.connect(self._btnWeb, SIGNAL("clicked()"), lambda: self._item_changed(2)) self.connect(self._btnFind, SIGNAL("clicked()"), lambda: self._item_changed(3)) self.connect(btn_close, SIGNAL('clicked()'), self.hide) def gain_focus(self): self._console.setFocus() def _item_changed(self, val): if not self.isVisible(): self.show() self.stack.show_display(val) def show_find_in_files_widget(self): index_of = self.stack.indexOf(self._findInFilesWidget) self._item_changed(index_of) self._findInFilesWidget.open() def show_find_occurrences(self, word): index_of = self.stack.indexOf(self._findInFilesWidget) self._item_changed(index_of) self._findInFilesWidget.find_occurrences(word) def load_toolbar(self, toolbar): toolbar.addWidget(self._combo) toolbar.addSeparator() def run_application(self, fileName, pythonPath=False, PYTHONPATH=None, programParams='', preExec='', postExec=''): self._item_changed(1) self.show() self._runWidget.start_process(fileName, pythonPath, PYTHONPATH, programParams, preExec, postExec) self._runWidget.input.setFocus() def show_results(self, items): self._item_changed(4) self.show() self._results.update_result(items) self._results._tree.setFocus() def kill_application(self): self._runWidget.kill_process() def render_web_page(self, url): self._item_changed(2) self.show() self._web.render_page(url) if settings.SHOW_WEB_INSPECTOR: explorer_container.ExplorerContainer().set_inspection_page( self._web.webFrame.page()) self._web.webFrame.triggerPageAction(QWebPage.InspectElement, True) explorer_container.ExplorerContainer().refresh_inspector() def add_to_stack(self, widget, icon_path, description): """ Add a widget to the container and an button(with icon))to the toolbar to show the widget """ #add the widget self.stack.addWidget(widget) #create a button in the toolbar to show the widget button = QPushButton(QIcon(icon_path), '') button.setToolTip(description) func = lambda: self._item_changed(self.stack.count() - 1) self.connect(button, SIGNAL("clicked()"), func) self.__toolbar.addWidget(button)
class NumberBoxPanel(QWidget): def __init__(self, parent, resoution = "0.0000"): QWidget.__init__(self, parent) while not isinstance(parent, QDialog): parent = parent.parent() self.setObjectName("NumberBoxPanel" + str(len(parent.findChildren(NumberBoxPanel)))) self.hLayoutBoxPanel = QHBoxLayout(self) self.hLayoutBoxPanel.setSpacing(0) self.hLayoutBoxPanel.setContentsMargins(0,0,0,0) self.hLayoutBoxPanel.setObjectName(("hLayoutBoxPanel")) self.frameBoxPanel = QFrame(self) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frameBoxPanel.sizePolicy().hasHeightForWidth()) self.frameBoxPanel.setSizePolicy(sizePolicy) self.frameBoxPanel.setFrameShape(QFrame.NoFrame) self.frameBoxPanel.setFrameShadow(QFrame.Raised) self.frameBoxPanel.setObjectName(("frameBoxPanel")) self.hLayoutframeBoxPanel = QHBoxLayout(self.frameBoxPanel) self.hLayoutframeBoxPanel.setSpacing(0) self.hLayoutframeBoxPanel.setMargin(0) self.hLayoutframeBoxPanel.setObjectName(("hLayoutframeBoxPanel")) self.captionLabel = QLabel(self.frameBoxPanel) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.captionLabel.sizePolicy().hasHeightForWidth()) self.captionLabel.setSizePolicy(sizePolicy) self.captionLabel.setMinimumSize(QSize(200, 0)) self.captionLabel.setMaximumSize(QSize(200, 16777215)) font = QFont() font.setBold(False) font.setWeight(50) self.captionLabel.setFont(font) self.captionLabel.setObjectName(("captionLabel")) self.hLayoutframeBoxPanel.addWidget(self.captionLabel) if resoution != None: self.numberBox = QLineEdit(self.frameBoxPanel) self.numberBox.setEnabled(True) font = QFont() font.setBold(False) font.setWeight(50) self.numberBox.setFont(font) self.numberBox.setObjectName(self.objectName() + "_numberBox") self.numberBox.setText("0.0") self.numberBox.setMinimumWidth(70) self.numberBox.setMaximumWidth(70) self.hLayoutframeBoxPanel.addWidget(self.numberBox) self.numberBox.textChanged.connect(self.numberBoxChanged) self.numberBox.editingFinished.connect(self.numberBoxEditingFinished) else: self.numberBox = QSpinBox(self.frameBoxPanel) self.numberBox.setObjectName(self.objectName() + "_numberBox") self.numberBox.setMinimumWidth(70) self.numberBox.setMaximumWidth(70) self.numberBox.setMinimum(-100000000) self.numberBox.setMaximum(100000000) self.numberBox.setValue(1) self.hLayoutframeBoxPanel.addWidget(self.numberBox) self.imageButton = QPushButton(self.frameBoxPanel) self.imageButton.setText(("")) icon = QIcon() icon.addPixmap(QPixmap(("Resource/convex_hull.png")), QIcon.Normal, QIcon.Off) self.imageButton.setIcon(icon) self.imageButton.setObjectName(("imageButton")) self.imageButton.setVisible(False) self.hLayoutframeBoxPanel.addWidget(self.imageButton) self.hLayoutBoxPanel.addWidget(self.frameBoxPanel) spacerItem = QSpacerItem(10,10,QSizePolicy.Expanding, QSizePolicy.Minimum) self.hLayoutBoxPanel.addItem(spacerItem) self.imageButton.clicked.connect(self.imageButtonClicked) self.numberResolution = resoution str0 = String.Number2String(6.6788, "0.0000") self.Value = 0 self.captionUnits = "" def imageButtonClicked(self): self.emit(SIGNAL("Event_1"), self) def method_6(self, string_0): return "%s%s\t%f %s"%(string_0, self.Caption, self.Value, self.CaptionUnits); def numberBoxEditingFinished(self): self.emit(SIGNAL("editingFinished"), self) def numberBoxChanged(self): try: test = float(self.numberBox.text()) self.emit(SIGNAL("Event_0"), self) except: if self.numberBox.text() == "" or self.numberBox.text() == "-" or self.numberBox.text() == "+": return str0 = "You must input the float type in \"%s\"."%(self.Caption) QMessageBox.warning(self, "Warning" , str0) self.numberBox.setText("0.0") def get_CaptionUnits(self): return self.captionUnits def set_CaptionUnits(self, captionUnits): self.captionUnits = captionUnits CaptionUnits = property(get_CaptionUnits, set_CaptionUnits, None, None) def get_Caption(self): caption = self.captionLabel.text() findIndex = caption.indexOf("(") if findIndex > 0: val = caption.left(findIndex) return val return caption def set_Caption(self, captionStr): if self.CaptionUnits != "" and self.CaptionUnits != None: self.captionLabel.setText(QString(captionStr + "(") + self.CaptionUnits + QString("):")) else: self.captionLabel.setText(captionStr + ":") Caption = property(get_Caption, set_Caption, None, None) def get_Visible(self): return self.isVisible() def set_Visible(self, bool): self.setVisible(bool) Visible = property(get_Visible, set_Visible, None, None) def get_Value(self): try: if self.numberResolution != None: return float(self.numberBox.text()) else: return self.numberBox.value() except: return 0.0 def set_Value(self, valueFloat): if self.numberResolution != None: if valueFloat == None or valueFloat == "": rStr = String.Number2String(0, self.numberResolution) self.numberBox.setText(rStr) return try: test = float(valueFloat) rStr = String.Number2String(test, self.numberResolution) self.numberBox.setText(rStr) except: str0 = "You must put the float type in \"%s\"."%(self.Caption) QMessageBox.warning(self, "Warning" , str0) rStr = String.Number2String(0, self.numberResolution) self.numberBox.setText(rStr) else: try: test = int(valueFloat) self.numberBox.setValue(test) except: str0 = "You must put the float type in \"%s\"."%(self.Caption) QMessageBox.warning(self, "Warning" , str0) self.numberBox.setValue(0) Value = property(get_Value, set_Value, None, None) # def get_IsEmpty(self): # return self.numberBox.text() == "" or self.numberBox.text() == None # IsEmpty = property(get_IsEmpty, None, None, None) def get_ReadOnly(self): return self.numberBox.isReadOnly() def set_ReadOnly(self, bool): self.numberBox.setReadOnly(bool) ReadOnly = property(get_ReadOnly, set_ReadOnly, None, None) def set_LabelWidth(self, width): self.captionLabel.setMinimumSize(QSize(width, 0)) self.captionLabel.setMaximumSize(QSize(width, 16777215)) LabelWidth = property(None, set_LabelWidth, None, None) def set_Width(self, width): self.numberBox.setMinimumSize(QSize(width, 0)) self.numberBox.setMaximumSize(QSize(width, 16777215)) Width = property(None, set_Width, None, None) def get_Enabled(self): return self.isEnabled() def set_Enabled(self, bool): self.setEnabled(bool) Enabled = property(get_Enabled, set_Enabled, None, None) def set_Button(self, imageName): if imageName == None or imageName == "": self.imageButton.setVisible(False) return icon = QIcon() icon.addPixmap(QPixmap(("Resource/" + imageName)), QIcon.Normal, QIcon.Off) self.imageButton.setIcon(icon) self.imageButton.setVisible(True) Button = property(None, set_Button, None, None)
def __createStatusLayout(self): ## Make the currently running, start and stop button, running status self.__currentPatternLabel = QLabel(PATTERN_PREAMBLE + EMPTY_PATTERN_SELECTED) font = self.__currentPatternLabel.font() self.__setFont(self.__currentPatternLabel, CONTROL_LABEL_FONT_SIZE) self.__currentStatusLabel = QLabel(STATUS_PREAMBLE + STOPPED) self.__setFont(self.__currentStatusLabel, CONTROL_LABEL_FONT_SIZE) self.StartButton = QPushButton("Start") self.__setFont(self.StartButton, CONTROL_BUTTON_FONT_SIZE) self.StartButton.setMinimumSize(CONTROL_BUTTON_WIDTH, CONTROL_BUTTON_HEIGHT) startIcon = QIcon(START_ICON_LOC) stopIcon = QIcon(STOP_ICON_LOC) self.StartButton.setIcon(startIcon) self.StopButton = QPushButton("Stop") self.__setFont(self.StopButton, CONTROL_BUTTON_FONT_SIZE) self.StopButton.setIcon(stopIcon) self.StopButton.setMinimumSize(CONTROL_BUTTON_WIDTH, CONTROL_BUTTON_HEIGHT) self.StartButton.clicked.connect(self.__handleStart) self.StopButton.clicked.connect(self.__handleStop) # put on the first row of the left coloumn, first two of the right column controlLayout = QHBoxLayout() leftHandColumn = QVBoxLayout() rightHandColumn = QVBoxLayout() leftHandColumn.addWidget(self.__currentPatternLabel) rightHandColumn.addWidget(self.__currentStatusLabel) startStopLayout = QHBoxLayout() startStopLayout.addWidget(self.StartButton) startStopLayout.addWidget(self.StopButton) rightHandColumn.addLayout(startStopLayout) ## Make Intensity Layout self.__intensityLabel = QLabel(INTENSITY_PREAMBLE + str(self.__currentIntensity)) self.__setFont(self.__intensityLabel, CONTROL_LABEL_FONT_SIZE) self.__intensityButton = QPushButton("Set Intensity...") self.__setFont(self.__intensityButton, CONTROL_BUTTON_FONT_SIZE) self.__intensityButton.setMinimumSize(CONTROL_BUTTON_WIDTH * 2, CONTROL_BUTTON_HEIGHT) self.__intensityButton.setMaximumSize(CONTROL_BUTTON_WIDTH * 2, CONTROL_BUTTON_HEIGHT) self.__intensityButton.clicked.connect(self.__intensityButtonClicked) intensityIcon = QIcon(INTENSITY_ICON_LOC) self.__intensityButton.setIcon(intensityIcon) intensityLayout = QVBoxLayout() intensityLayout.addWidget(self.__intensityLabel) intensityLayout.addWidget(self.__intensityButton) # add intensity layout to left hand column leftHandColumn.addLayout(intensityLayout) # Add shutdown button self.ShutdownButton = QPushButton("Shutdown") self.__setFont(self.ShutdownButton, CONTROL_BUTTON_FONT_SIZE) self.ShutdownButton.setMinimumSize(160, CONTROL_BUTTON_HEIGHT) shutdownIcon = QIcon(SHUTDOWN_ICON_LOC) self.ShutdownButton.setIcon(shutdownIcon) self.ShutdownButton.clicked.connect(self.__shutdown) rightHandColumn.addWidget(self.ShutdownButton) infoBarLayout = QHBoxLayout() infoBarLayout.addLayout(leftHandColumn) infoBarLayout.addStretch(1) infoBarLayout.addLayout(rightHandColumn) return infoBarLayout
def initControls(self): self.main_frame = QWidget() self.plot3 = Qwt.QwtPlot(self) self.plot3.setCanvasBackground(Qt.white) self.plot3.enableAxis(Qwt.QwtPlot.yLeft, False) self.plot3.enableAxis(Qwt.QwtPlot.xBottom, False) self.plot1 = Qwt.QwtPlot(self) self.plot1.setCanvasBackground(Qt.white) top1_hbox = QHBoxLayout() SeacherButton = QPushButton("&Select") FrontButton = QPushButton("<<") LaterButton = QPushButton(">>") self.connect(SeacherButton, SIGNAL('clicked()'), self.SeacherButton) self.connect(FrontButton, SIGNAL('clicked()'), self.FrontButton) self.connect(LaterButton, SIGNAL('clicked()'), self.LaterButton) FrontButton.setFixedWidth(50) SeacherButton.setFixedWidth(100) LaterButton.setFixedWidth(50) top1_hbox.addWidget(FrontButton) top1_hbox.addWidget(SeacherButton) top1_hbox.addWidget(LaterButton) self.id=self.row self.ID_label = QLabel("Entry No. %s Of 212964 Libaray Name:Nist2011 "%(self.id+1)) top1_hbox.addWidget(self.ID_label) top2_hbox = QHBoxLayout() Name_label = QLabel("Name:") Name_label.setFixedWidth(70) self.Name_edit = QLineEdit() #Name_edit.setFixedWidth(150) top2_hbox.addWidget(Name_label) top2_hbox.addWidget(self.Name_edit) top3_hbox = QHBoxLayout() Formula_label = QLabel("Formula:") Formula_label.setFixedWidth(70) self.Formula_edit = QLineEdit() #Name_edit.setFixedWidth(150) top3_hbox.addWidget(Formula_label) top3_hbox.addWidget(self.Formula_edit) top4_hbox = QHBoxLayout() MW_label = QLabel("MW:") MW_label.setFixedWidth(70) self.MW_edit = QLineEdit() ExactMW_label = QLabel("Exact Mass:") ExactMW_label.setFixedWidth(70) self.ExactMW_edit = QLineEdit() Cas_label = QLabel("CAS#:") Cas_label.setFixedWidth(70) self.Cas_edit = QLineEdit() Nist_label = QLabel("NIST#:") Nist_label.setFixedWidth(70) self.Nist_edit = QLineEdit() top4_hbox.addWidget(MW_label) top4_hbox.addWidget(self.MW_edit) top4_hbox.addWidget(ExactMW_label) top4_hbox.addWidget(self.ExactMW_edit) top4_hbox.addWidget(Cas_label) top4_hbox.addWidget(self.Cas_edit) top4_hbox.addWidget(Nist_label) top4_hbox.addWidget(self.Nist_edit) top5_hbox = QHBoxLayout() Cont_label = QLabel("Contributor:") Cont_label.setFixedWidth(70) self.Cont_edit = QLineEdit() #Name_edit.setFixedWidth(150) top5_hbox.addWidget(Cont_label) top5_hbox.addWidget(self.Cont_edit) top6_hbox = QHBoxLayout() Peak_label = QLabel("10 largest peaks:") Peak_label.setFixedWidth(100) self.Peak_edit = QLineEdit() #Name_edit.setFixedWidth(150) top6_hbox.addWidget(Peak_label) top6_hbox.addWidget(self.Peak_edit) top_Vbox = QVBoxLayout() top_Vbox.addLayout(top1_hbox) top_Vbox.addLayout(top2_hbox) top_Vbox.addLayout(top3_hbox) top_Vbox.addLayout(top4_hbox) top_Vbox.addLayout(top5_hbox) top_Vbox.addLayout(top6_hbox) below_hbox = QHBoxLayout() below_hbox.addWidget(self.plot1,3) below_hbox.addWidget(self.plot3,1) hbox = QVBoxLayout() hbox.addLayout(top_Vbox) hbox.addLayout(below_hbox) self.setLayout(hbox)
def __init__(self, parent, resoution = "0.0000"): QWidget.__init__(self, parent) while not isinstance(parent, QDialog): parent = parent.parent() self.setObjectName("NumberBoxPanel" + str(len(parent.findChildren(NumberBoxPanel)))) self.hLayoutBoxPanel = QHBoxLayout(self) self.hLayoutBoxPanel.setSpacing(0) self.hLayoutBoxPanel.setContentsMargins(0,0,0,0) self.hLayoutBoxPanel.setObjectName(("hLayoutBoxPanel")) self.frameBoxPanel = QFrame(self) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.frameBoxPanel.sizePolicy().hasHeightForWidth()) self.frameBoxPanel.setSizePolicy(sizePolicy) self.frameBoxPanel.setFrameShape(QFrame.NoFrame) self.frameBoxPanel.setFrameShadow(QFrame.Raised) self.frameBoxPanel.setObjectName(("frameBoxPanel")) self.hLayoutframeBoxPanel = QHBoxLayout(self.frameBoxPanel) self.hLayoutframeBoxPanel.setSpacing(0) self.hLayoutframeBoxPanel.setMargin(0) self.hLayoutframeBoxPanel.setObjectName(("hLayoutframeBoxPanel")) self.captionLabel = QLabel(self.frameBoxPanel) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.captionLabel.sizePolicy().hasHeightForWidth()) self.captionLabel.setSizePolicy(sizePolicy) self.captionLabel.setMinimumSize(QSize(200, 0)) self.captionLabel.setMaximumSize(QSize(200, 16777215)) font = QFont() font.setBold(False) font.setWeight(50) self.captionLabel.setFont(font) self.captionLabel.setObjectName(("captionLabel")) self.hLayoutframeBoxPanel.addWidget(self.captionLabel) if resoution != None: self.numberBox = QLineEdit(self.frameBoxPanel) self.numberBox.setEnabled(True) font = QFont() font.setBold(False) font.setWeight(50) self.numberBox.setFont(font) self.numberBox.setObjectName(self.objectName() + "_numberBox") self.numberBox.setText("0.0") self.numberBox.setMinimumWidth(70) self.numberBox.setMaximumWidth(70) self.hLayoutframeBoxPanel.addWidget(self.numberBox) self.numberBox.textChanged.connect(self.numberBoxChanged) self.numberBox.editingFinished.connect(self.numberBoxEditingFinished) else: self.numberBox = QSpinBox(self.frameBoxPanel) self.numberBox.setObjectName(self.objectName() + "_numberBox") self.numberBox.setMinimumWidth(70) self.numberBox.setMaximumWidth(70) self.numberBox.setMinimum(-100000000) self.numberBox.setMaximum(100000000) self.numberBox.setValue(1) self.hLayoutframeBoxPanel.addWidget(self.numberBox) self.imageButton = QPushButton(self.frameBoxPanel) self.imageButton.setText(("")) icon = QIcon() icon.addPixmap(QPixmap(("Resource/convex_hull.png")), QIcon.Normal, QIcon.Off) self.imageButton.setIcon(icon) self.imageButton.setObjectName(("imageButton")) self.imageButton.setVisible(False) self.hLayoutframeBoxPanel.addWidget(self.imageButton) self.hLayoutBoxPanel.addWidget(self.frameBoxPanel) spacerItem = QSpacerItem(10,10,QSizePolicy.Expanding, QSizePolicy.Minimum) self.hLayoutBoxPanel.addItem(spacerItem) self.imageButton.clicked.connect(self.imageButtonClicked) self.numberResolution = resoution str0 = String.Number2String(6.6788, "0.0000") self.Value = 0 self.captionUnits = ""
def __init__(self, files, tab, delete, parent, test=False): """ Keyword arguments: files -- list with dicts containing file names tab -- instanseof AudioVideoTab, ImageTab or DocumentTab indicating currently active tab delete -- boolean that shows if files must removed after conversion parent -- parent widget files: Each dict have only one key and one corresponding value. Key is a file to be converted and it's value is the name of the new file that will be converted. Example list: [{"/foo/bar.png" : "/foo/bar.bmp"}, {"/f/bar2.png" : "/f/bar2.bmp"}] """ super(Progress, self).__init__(parent) self.parent = parent self.files = files self.num_total_files = len(self.files) self.tab = tab self.delete = delete if not test: self._type = tab.name self.step = int(100 / len(files)) self.ok = 0 self.error = 0 self.running = True self.nowQL = QLabel(self.tr('In progress: ')) totalQL = QLabel(self.tr('Total:')) self.nowQPBar = QProgressBar() self.nowQPBar.setValue(0) self.totalQPBar = QProgressBar() self.totalQPBar.setValue(0) self.cancelQPB = QPushButton(self.tr('Cancel')) detailsQPB = QCommandLinkButton(self.tr('Details')) detailsQPB.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) detailsQPB.setCheckable(True) detailsQPB.setMaximumWidth(113) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.outputQTE = QTextEdit() self.outputQTE.setReadOnly(True) self.frame = QFrame() frame_layout = utils.add_to_layout('h', self.outputQTE) self.frame.setLayout(frame_layout) self.frame.hide() hlayout = utils.add_to_layout('h', None, self.nowQL, None) hlayout2 = utils.add_to_layout('h', None, totalQL, None) hlayout3 = utils.add_to_layout('h', detailsQPB, line) hlayout4 = utils.add_to_layout('h', self.frame) hlayout5 = utils.add_to_layout('h', None, self.cancelQPB) vlayout = utils.add_to_layout('v', hlayout, self.nowQPBar, hlayout2, self.totalQPBar, None, hlayout3, hlayout4, hlayout5) self.setLayout(vlayout) detailsQPB.toggled.connect(self.resize_dialog) detailsQPB.toggled.connect(self.frame.setVisible) self.cancelQPB.clicked.connect(self.reject) self.file_converted_signal.connect(self.next_file) self.refr_bars_signal.connect(self.refresh_progress_bars) self.update_text_edit_signal.connect(self.update_text_edit) self.resize(484, 200) self.setWindowTitle('FF Multi Converter - ' + self.tr('Conversion')) if not test: self.get_data() # should be first and not in QTimer.singleShot() QTimer.singleShot(0, self.manage_conversions)
def __init__(self): QWidget.__init__(self) self.shortcuts_text = { "Duplicate": self.tr("Duplicate the line/selection"), "Remove-line": self.tr("Remove the line/selection"), "Move-up": self.tr("Move the line/selection up"), "Move-down": self.tr("Move the line/selection down"), "Close-tab": self.tr("Close the current tab"), "New-file": self.tr("Create a New tab"), "New-project": self.tr("Create a new Project"), "Open-file": self.tr("Open a File"), "Open-project": self.tr("Open a Project"), "Save-file": self.tr("Save the current file"), "Save-project": self.tr("Save the current project opened files"), "Print-file": self.tr("Print current file"), "Redo": self.tr("Redo"), "Comment": self.tr("Comment line/selection"), "Uncomment": self.tr("Uncomment line/selection"), "Horizontal-line": self.tr("Insert Horizontal line"), "Title-comment": self.tr("Insert comment Title"), "Indent-less": self.tr("Indent less"), "Hide-misc": self.tr("Hide Misc Container"), "Hide-editor": self.tr("Hide Editor Area"), "Hide-explorer": self.tr("Hide Explorer"), "Run-file": self.tr("Execute current file"), "Run-project": self.tr("Execute current project"), "Debug": self.tr("Debug"), "Switch-Focus": self.tr("Switch keyboard focus"), "Stop-execution": self.tr("Stop Execution"), "Hide-all": self.tr("Hide all (Except Editor)"), "Full-screen": self.tr("Full Screen"), "Find": self.tr("Find"), "Find-replace": self.tr("Find & Replace"), "Find-with-word": self.tr("Find word under cursor"), "Find-next": self.tr("Find Next"), "Find-previous": self.tr("Find Previous"), "Help": self.tr("Show Python Help"), "Split-horizontal": self.tr("Split Tabs Horizontally"), "Split-vertical": self.tr("Split Tabs Vertically"), "Follow-mode": self.tr("Activate/Deactivate Follow Mode"), "Reload-file": self.tr("Reload File"), "Jump": self.tr("Jump to line"), "Find-in-files": self.tr("Find in Files"), "Import": self.tr("Import from everywhere"), "Go-to-definition": self.tr("Go to definition"), "Complete-Declarations": self.tr("Complete Declarations"), "Code-locator": self.tr("Show Code Locator"), "File-Opener": self.tr("Show File Opener"), "Navigate-back": self.tr("Navigate Back"), "Navigate-forward": self.tr("Navigate Forward"), "Open-recent-closed": self.tr("Open recent closed file"), "Change-Tab": self.tr("Change to the next Tab"), "Change-Tab-Reverse": self.tr("Change to the previous Tab"), "Show-Code-Nav": self.tr("Activate History Navigation"), "Show-Bookmarks-Nav": self.tr("Activate Bookmarks Navigation"), "Show-Breakpoints-Nav": self.tr("Activate Breakpoints Navigation"), "Show-Paste-History": self.tr("Show copy/paste history"), "History-Copy": self.tr("Copy into copy/paste history"), "History-Paste": self.tr("Paste from copy/paste history"), "change-split-focus": self.tr("Change the keyboard focus between the current splits"), "Add-Bookmark-or-Breakpoint": self.tr("Insert Bookmark/Breakpoint"), "move-tab-to-next-split": self.tr("Move the current Tab to the next split."), "change-tab-visibility": self.tr("Show/Hide the Tabs in the Editor Area."), "Highlight-Word": self.tr("Highlight occurrences for word under cursor") } self.shortcut_dialog = ShortcutDialog(self) #main layout main_vbox = QVBoxLayout(self) #layout for buttons buttons_layout = QVBoxLayout() #widgets self.result_widget = TreeResult() load_defaults_button = QPushButton(self.tr("Load defaults")) #add widgets main_vbox.addWidget(self.result_widget) buttons_layout.addWidget(load_defaults_button) main_vbox.addLayout(buttons_layout) main_vbox.addWidget( QLabel( self.tr("The Shortcut's Text in the Menus are " "going to be refreshed on restart."))) #load data! self.result_widget.setColumnWidth(0, 400) self._load_shortcuts() #signals #open the set shortcut dialog self.connect(self.result_widget, SIGNAL("itemDoubleClicked(QTreeWidgetItem*, int)"), self._open_shortcut_dialog) #load defaults shortcuts self.connect(load_defaults_button, SIGNAL("clicked()"), self._load_defaults_shortcuts) #one shortcut has changed self.connect(self.shortcut_dialog, SIGNAL('shortcutChanged'), self._shortcut_changed)