class DialogSaveFiles(QDialog): def __init__(self, files, editor_container, parent): QDialog.__init__(self, parent) self.setWindowTitle(self.tr("Archivos no guardados!")) self._event_ignore = False self._editor_container = editor_container vLayout = QVBoxLayout(self) label = QLabel(self.tr("Los siguientes archivos se han modificado. " "Guardarlos?")) vLayout.addWidget(label) self.list_widget = QListWidget() self.list_widget.setSelectionMode(QAbstractItemView.ExtendedSelection) for e, _file in enumerate(files): if not _file: _file = "Untitled" self.list_widget.addItem(_file) self.list_widget.item(e).setSelected(True) vLayout.addWidget(self.list_widget) box_buttons = QHBoxLayout() btn_nothing = QPushButton(self.tr("Ninguno")) btn_save = QPushButton(self.tr("Guardar Selección")) btn_cancel = QPushButton(self.tr("Cancelar")) box_buttons.addWidget(btn_nothing) box_buttons.addWidget(btn_save) box_buttons.addWidget(btn_cancel) vLayout.addLayout(box_buttons) self.key_scape = QShortcut(QKeySequence(Qt.Key_Escape), self) # Conexiones self.connect(self.key_scape, SIGNAL("activated()"), self._ignore) self.connect(btn_nothing, SIGNAL("clicked()"), self.close) self.connect(btn_save, SIGNAL("clicked()"), self._save) self.connect(btn_cancel, SIGNAL("clicked()"), self._ignore) def _ignore(self): self._event_ignore = True self.hide() def ignorado(self): return self._event_ignore def _save(self): selected_files = self.list_widget.selectedItems() for _file in selected_files: filename = _file.text() self._editor_container.save_selected(filename) self.close()
class SelectFromListDialog(QDialog): def __init__(self, options, parent=None, title=''): super(SelectFromListDialog, self).__init__(parent) layout = QVBoxLayout(self) self.setWindowTitle(title) self.setStyleSheet("background-color: rgb(245,247,255);") # nice widget for editing the date self.selector = QListWidget(self) self.selector.addItems(list(options)) layout.addWidget(self.selector) # OK and Cancel buttons self.buttons = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self) layout.addWidget(self.buttons) self.buttons.accepted.connect(self.accept) self.buttons.rejected.connect(self.reject) def selected(self): items = self.selector.selectedItems() q_text = items[0].text() return str(q_text) @staticmethod def get_selected(options, parent=None, title=''): dialog = SelectFromListDialog(options, parent, title) dialog.selector.setItemSelected(dialog.selector.item(0), True) result = dialog.exec_() focus = dialog.selected() return focus, result == QDialog.Accepted
class VariableListBox(QWidget): def __init__(self, id, text, sep=","): QWidget.__init__(self) self.widget = QListWidget() self.widget.setToolTip(text) self.widget.setSelectionMode(QAbstractItemView.ExtendedSelection) label = QLabel(text) label.setBuddy(self.widget) vbox = VBoxLayout() vbox.addWidget(label) vbox.addWidget(self.widget) self.setLayout(vbox) self.id = id self.sep = sep def parameterValues(self): self.widget.selectAll() items = self.widget.selectedItems() first = True var = QString() for item in items: if first: var.append(item.text()) first = False else: var.append("%s%s" % (self.sep, item.text())) if var.isEmpty(): raise Exception("Error: Insufficient number of input variables") params = {self.id:var} return params
class MergeDialog(QDialog): def __init__(self, track_panels, parent = None): QDialog.__init__(self, parent) self.track_panels = track_panels self.layout = QVBoxLayout(self) self.list = QListWidget(self) self.list.setSelectionMode(QAbstractItemView.MultiSelection) for tv in track_panels: name = tv.curve_source.name() self.list.addItem(QListWidgetItem(name, self.list)) self.ok_button = QPushButton("ok", self) minimum_size_policy(self.ok_button) QWidget.connect(self.ok_button, SIGNAL("clicked()"), self.accept) self.list.updateGeometry() self.layout.addWidget(self.list) self.layout.addWidget(self.ok_button) self.updateGeometry() self.adjustSize() def selected_track_panels(self): selected = self.list.selectedItems() names = [s.text() for s in selected] return [tv for tv in self.track_panels if tv.curve_source.name() in names]
class FinishPage(QWizardPage): def __init__(self): super(FinishPage, self).__init__() container = QVBoxLayout(self) self.setSubTitle(self.tr("Elige una plantilla")) self.list_template = QListWidget() self.list_template.addItem(self.tr("Proyecto en blanco")) self.list_template.addItem(self.tr("Incluir achivo y función main")) container.addWidget(self.list_template) @property def template(self): selection = self.list_template.selectedItems() if not selection: self.list_template.currentItem().setSelected(True) return self.list_template.row(self.list_template.selectedItems()[0])
class CustomFieldsEditor(QDialog): def __init__(self, parent, fields): QDialog.__init__(self, parent) layout = QVBoxLayout(self) self._list_elements = QListWidget(self) self._fields = dict(fields) for field, ftype in fields.items(): self._list_elements.addItem(field + ' (' + ftype + ')') self._list_elements.setSelectionMode( QAbstractItemView.ExtendedSelection) layout.addWidget(self._list_elements) add_remove = AddRemoveButtonBar(self, 'Remove selected field(s)', self.remove, 'Add field', self.add) layout.addWidget(add_remove) buttons = QWidget(self) buttons_layout = QHBoxLayout() buttons.setLayout(buttons_layout) buttons_layout.addStretch() ok_button = QPushButton("Ok") cancel_button = QPushButton("Cancel") ok_button.clicked.connect(self.accept) cancel_button.clicked.connect(self.reject) buttons_layout.addWidget(ok_button) buttons_layout.addWidget(cancel_button) layout.addWidget(buttons) self.setLayout(layout) def remove(self): res = [] for item in self._list_elements.selectedItems(): del self._fields[str(item.text()).split(' ')[0]] res.append(self._list_elements.row(item)) for row in sorted(res, key=lambda x: -x): self._list_elements.takeItem(row) def add(self): dialog = AddFieldDialog(self) if dialog.exec_(): self._fields[str(dialog.name)] = dialog.ftype self._list_elements.addItem(dialog.name + ' (' + dialog.ftype + ')') def get_fields(self): return self._fields
class RMirrorBrowser(QDialog): def __init__(self, parent=None): QDialog.__init__(self, parent) kwargs = {"local.only":False} m = robjects.r.getCRANmirrors(all=False, **kwargs) names = QStringList(list(m.rx('Name')[0])) urls = list(m.rx('URL')[0]) self.links = dict(zip(names, urls)) names = QStringList(names) self.setWindowTitle("manageR - Choose CRAN Mirror") self.setWindowIcon(QIcon(":icon")) self.links = dict(zip(names, urls)) self.currentMirror = None self.mirrorList = QListWidget(self) self.mirrorList.setAlternatingRowColors(True) self.mirrorList.setEditTriggers(QAbstractItemView.NoEditTriggers) self.mirrorList.setSortingEnabled(True) self.mirrorList.setSelectionMode(QAbstractItemView.SingleSelection) self.mirrorList.setToolTip("Double-click to select mirror location") self.mirrorList.setWhatsThis("List of CRAN mirrors") self.mirrorList.insertItems(0, names) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel) vbox = QVBoxLayout(self) vbox.addWidget(self.mirrorList) vbox.addWidget(buttonBox) self.connect(buttonBox, SIGNAL("accepted()"), self.accept) self.connect(buttonBox, SIGNAL("rejected()"), self.reject) self.connect(self.mirrorList, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.accept) def currentMirror(self): return robjects.r("getOption('repos')")[0] def setCurrentMirror(self, mirror): robjects.r("options('repos'='%s')" % mirror) def accept(self): items = self.mirrorList.selectedItems() if len(items) > 0: name = items[0].text() url = self.links[name] self.setCurrentMirror(url) QDialog.accept(self) else: QMessageBox.warning(self, "manageR - Warning", "Please choose a valid CRAN mirror")
class MultipleChoiceDialog(QDialog): def __init__(self, parent, title, text, items): QDialog.__init__(self, parent) self.setWindowTitle(title) self.layout = QVBoxLayout() label = QLabel(text) self.layout.addWidget(label) self.listwidget = QListWidget(self) self.listwidget.setSelectionMode(QAbstractItemView.ExtendedSelection) for item in items: self.listwidget.addItem(item) self.layout.addWidget(self.listwidget) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) self.layout.addWidget(buttonBox) self.setLayout(self.layout) def selectedItems(self): return self.listwidget.selectedItems()
class IndexDialog(QDialog): def __init__(self, track_panel, parent = None): QDialog.__init__(self, parent) self.track_panel = track_panel self.layout = QVBoxLayout(self) self.list = QListWidget(self) curve_names = self.track_panel.curve_source.available_curves() for curve_name in curve_names: self.list.addItem(QListWidgetItem(curve_name, self.list)) self.ok_button = QPushButton("ok", self) minimum_size_policy(self.ok_button) QWidget.connect(self.ok_button, SIGNAL("clicked()"), self.accept) self.list.updateGeometry() self.layout.addWidget(self.list) self.layout.addWidget(self.ok_button) self.updateGeometry() self.adjustSize() def index(self): selected, = self.list.selectedItems() return selected.text()
class ChainComposerDialog(QDialog): def __init__(self, parent=None): super(ChainComposerDialog, self).__init__(parent) self.setWindowTitle("Composer Chain") layout = QVBoxLayout() mainLayout = QHBoxLayout() selectionLayout = QVBoxLayout() label = QLabel("Available Filters:") selectionLayout.addWidget(label) self.__selectionList = QListWidget() selectionLayout.addWidget(self.__selectionList) mainLayout.addLayout(selectionLayout) actionsLayout = QVBoxLayout() actionsLayout.addStretch() addButton = QPushButton("Add>>") addButton.clicked.connect(self.__handleAdd) actionsLayout.addWidget(addButton) removeButton = QPushButton("Remove") actionsLayout.addWidget(removeButton) removeAllButton = QPushButton("Remove All") actionsLayout.addWidget(removeAllButton) actionsLayout.addStretch() mainLayout.addLayout(actionsLayout) chainLayout = QVBoxLayout() chainLayout.addWidget(QLabel("Chain:")) self.__chainList = QListWidget() chainLayout.addWidget(self.__chainList) mainLayout.addLayout(chainLayout) layout.addLayout(mainLayout) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.okClick) buttonBox.rejected.connect(self.cancelClick) layout.addWidget(buttonBox) # buttonLayout = QHBoxLayout() # okButton = QPushButton('OK') # okButton.clicked.connect(self.accept) # buttonLayout.addWidget(okButton) # cancelButton = QPushButton('Cancel') # cancelButton.clicked.connect(self.reject) # buttonLayout.addWidget(cancelButton) # layout.addLayout(buttonLayout) self.setLayout(layout) self.__composer = None def okClick(self): print "OK!" self.accept() def cancelClick(self): print "Cancel" self.reject() def setComposer(self, composer): self.__composer = composer @property def selectionList(self): return self.__getStrings(self.__selectionList) @selectionList.setter def setSelectionList(self, filters): for i in xrange(self.__selectionList.count()): self.__selectionList.takeItem(i) self.__selectionList.addItems(filters) def filterAt(self, row): return self.__selectionList.item(row).text() def addToChain(self, filterName): self.__chainList.addItem(filterName) @property def composedFilter(self): return self.__getStrings(self.__chainList) @staticmethod def __getStrings(listWidget): return tuple(listWidget.item(i) for i in range(listWidget.count())) def __handleAdd(self): if self.__composer is None: return for item in self.__selectionList.selectedItems(): row = self.__selectionList.row(item) self.__composer.add(row)
class TraceWindow(QMainWindow): def __init__(self, params_pipe, number_pipe, data_pipe, mads_pipe, peaks_pipe, probe_path=None, screen_resolution=None): QMainWindow.__init__(self) # Receive parameters. params = params_pipe[0].recv() self.probe = load_probe(probe_path) self._nb_samples = params['nb_samples'] self._sampling_rate = params['sampling_rate'] self._display_list = list(range(self.probe.nb_channels)) self._params = { 'nb_samples': self._nb_samples, 'sampling_rate': self._sampling_rate, 'time': { 'min': 10.0, # ms 'max': 1000.0, # ms 'init': 100.0, # ms }, 'voltage': { 'min': 10.0, # µV 'max': 10e+3, # µV 'init': 20.0, # µV }, 'mads': { 'min': 0.0, # µV 'max': 100, # µV 'init': 3, # µV }, 'channels': self._display_list } self._canvas = TraceCanvas(probe_path=probe_path, params=self._params) central_widget = self._canvas.native # Create controls widgets. label_time = QLabel() label_time.setText(u"time") label_time_unit = QLabel() label_time_unit.setText(u"ms") self._dsp_time = QDoubleSpinBox() self._dsp_time.setMinimum(self._params['time']['min']) self._dsp_time.setMaximum(self._params['time']['max']) self._dsp_time.setValue(self._params['time']['init']) self._dsp_time.valueChanged.connect(self._on_time_changed) label_display_mads = QLabel() label_display_mads.setText(u"Display Mads") self._display_mads = QCheckBox() self._display_mads.stateChanged.connect(self._on_mads_display) label_display_peaks = QLabel() label_display_peaks.setText(u"Display Peaks") self._display_peaks = QCheckBox() self._display_peaks.stateChanged.connect(self._on_peaks_display) label_mads = QLabel() label_mads.setText(u"Mads") label_mads_unit = QLabel() label_mads_unit.setText(u"unit") self._dsp_mads = QDoubleSpinBox() self._dsp_mads.setMinimum(self._params['mads']['min']) self._dsp_mads.setMaximum(self._params['mads']['max']) self._dsp_mads.setValue(self._params['mads']['init']) self._dsp_mads.valueChanged.connect(self._on_mads_changed) label_voltage = QLabel() label_voltage.setText(u"voltage") label_voltage_unit = QLabel() label_voltage_unit.setText(u"µV") self._dsp_voltage = QDoubleSpinBox() self._dsp_voltage.setMinimum(self._params['voltage']['min']) self._dsp_voltage.setMaximum(self._params['voltage']['max']) self._dsp_voltage.setValue(self._params['voltage']['init']) self._dsp_voltage.valueChanged.connect(self._on_voltage_changed) # Color spikes self._color_spikes = QCheckBox() self._color_spikes.setText('See Spikes color') self._color_spikes.setCheckState(Qt.Checked) self._color_spikes.stateChanged.connect(self.display_spikes_color) # self._selection_channels.setGeometry(QtCore.QRect(10, 10, 211, 291)) spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) # Create controls grid. grid = QGridLayout() # # Add time row. grid.addWidget(label_time, 0, 0) grid.addWidget(self._dsp_time, 0, 1) grid.addWidget(label_time_unit, 0, 2) # # Add voltage row. grid.addWidget(label_voltage, 1, 0) grid.addWidget(self._dsp_voltage, 1, 1) grid.addWidget(label_voltage_unit, 1, 2) # # Add Mads widgets grid.addWidget(label_display_mads, 3, 0) grid.addWidget(self._display_mads, 3, 1) grid.addWidget(label_mads, 4, 0) grid.addWidget(self._dsp_mads, 4, 1) grid.addWidget(label_mads_unit, 4, 2) grid.addWidget(self._color_spikes, 5, 0) # # Add spacer. grid.addItem(spacer) # # Create info group. controls_group = QGroupBox() controls_group.setLayout(grid) self._selection_channels = QListWidget() self._selection_channels.setSelectionMode( QAbstractItemView.ExtendedSelection ) for i in range(self.probe.nb_channels): item = QListWidgetItem("Channel %i" % i) self._selection_channels.addItem(item) self._selection_channels.item(i).setSelected(True) def add_channel(): items = self._selection_channels.selectedItems() self._display_list = [] for i in range(len(items)): self._display_list.append(i) self._on_channels_changed() # self._selection_channels.itemClicked.connect(add_channel) nb_channel = self.probe.nb_channels self._selection_channels.itemSelectionChanged.connect(lambda: self.selected_channels(nb_channel)) # Create info grid. channels_grid = QGridLayout() # # Add Channel selection # grid.addWidget(label_selection, 3, 0) channels_grid.addWidget(self._selection_channels, 0, 1) # # Add spacer. channels_grid.addItem(spacer) # Create controls group. channels_group = QGroupBox() channels_group.setLayout(channels_grid) # # Create controls dock. channels_dock = QDockWidget() channels_dock.setWidget(channels_group) channels_dock.setWindowTitle("Channels selection") # # Create controls dock. control_dock = QDockWidget() control_dock.setWidget(controls_group) control_dock.setWindowTitle("Controls") # Create info widgets. label_time = QLabel() label_time.setText(u"time") self._label_time_value = QLineEdit() self._label_time_value.setText(u"0") self._label_time_value.setReadOnly(True) self._label_time_value.setAlignment(Qt.AlignRight) label_time_unit = QLabel() label_time_unit.setText(u"s") info_buffer_label = QLabel() info_buffer_label.setText(u"buffer") self._info_buffer_value_label = QLineEdit() self._info_buffer_value_label.setText(u"0") self._info_buffer_value_label.setReadOnly(True) self._info_buffer_value_label.setAlignment(Qt.AlignRight) info_buffer_unit_label = QLabel() info_buffer_unit_label.setText(u"") info_probe_label = QLabel() info_probe_label.setText(u"probe") info_probe_value_label = QLineEdit() info_probe_value_label.setText(u"{}".format(probe_path)) info_probe_value_label.setReadOnly(True) # TODO place the following info in another grid? info_probe_unit_label = QLabel() info_probe_unit_label.setText(u"") info_spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) # Create info grid. info_grid = QGridLayout() # # Time row. info_grid.addWidget(label_time, 0, 0) info_grid.addWidget(self._label_time_value, 0, 1) info_grid.addWidget(label_time_unit, 0, 2) # # Buffer row. info_grid.addWidget(info_buffer_label, 1, 0) info_grid.addWidget(self._info_buffer_value_label, 1, 1) info_grid.addWidget(info_buffer_unit_label, 1, 2) # # Probe row. info_grid.addWidget(info_probe_label, 2, 0) info_grid.addWidget(info_probe_value_label, 2, 1) info_grid.addWidget(info_probe_unit_label, 2, 2) # # Spacer. info_grid.addItem(info_spacer) # Create info group. info_group = QGroupBox() info_group.setLayout(info_grid) # Create info dock. info_dock = QDockWidget() info_dock.setWidget(info_group) info_dock.setWindowTitle("Info") # Create thread. thread = Thread(number_pipe, data_pipe, mads_pipe, peaks_pipe) thread.number_signal.connect(self._number_callback) thread.reception_signal.connect(self._reception_callback) thread.start() # Add dockable windows. self.addDockWidget(Qt.LeftDockWidgetArea, control_dock) self.addDockWidget(Qt.LeftDockWidgetArea, info_dock) self.addDockWidget(Qt.LeftDockWidgetArea, channels_dock) # Set central widget. self.setCentralWidget(central_widget) # Set window size. if screen_resolution is not None: screen_width = screen_resolution.width() screen_height = screen_resolution.height() self.resize(screen_width, screen_height) # Set window title. self.setWindowTitle("SpyKING Circus ORT - Read 'n' Qt display") print(" ") # TODO remove? def _number_callback(self, number): text = u"{}".format(number) self._info_buffer_value_label.setText(text) text = u"{:8.3f}".format(float(number) * float(self._nb_samples) / self._sampling_rate) self._label_time_value.setText(text) return def _reception_callback(self, data, mads, peaks): self._canvas.on_reception(data, mads, peaks) return def _on_time_changed(self): time = self._dsp_time.value() self._canvas.set_time(time) return def _on_voltage_changed(self): voltage = self._dsp_voltage.value() self._canvas.set_voltage(voltage) return def _on_mads_changed(self): mads = self._dsp_mads.value() self._canvas.set_mads(mads) return def _on_mads_display(self): value = self._display_mads.isChecked() self._canvas.show_mads(value) return def _on_peaks_display(self): value = self._display_peaks.isChecked() self._canvas.show_peaks(value) return def _on_channels_changed(self): self._canvas.set_channels(self._display_list) return def display_spikes_color(self, s): self._canvas.color_spikes(s) def selected_channels(self, max_channel): # print(self._selection_channels.selectedItems()) list_channel = [] for i in range(max_channel): if self._selection_channels.item(i).isSelected(): list_channel.append(i) self._canvas.selected_channels(list_channel) return
class AnnotationManager: def __init__(self, iface): locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(os.path.dirname(__file__), 'i18n', 'annotationManager_{}.qm'.format(locale)) self.translator = None if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) QCoreApplication.installTranslator(self.translator) self.iface = iface self.iface.projectRead.connect(self.projectOpen) self.dock = QDockWidget(self.tr('Annotations manager')) self.manager = QWidget() toolbar = QToolBar() self.annotationList = QListWidget() self.annotationList.itemClicked.connect(self.selectAnnotation) self.annotationList.itemChanged.connect(self.checkItem) action_refresh = QAction( QIcon(':/plugins/annotationManager/resources/mActionDraw.png'), self.tr('Refresh the annotations list'), self.manager) action_refresh.triggered.connect(self.refreshAnnotations) action_remove = QAction( QIcon( ':/plugins/annotationManager/resources/mActionRemoveAnnotation.png' ), self.tr('Remove the selected annotation'), self.manager) action_remove.triggered.connect(self.removeAnnotation) toolbar.addAction(action_refresh) toolbar.addAction(action_remove) toolbar.setIconSize(QSize(16, 16)) p1_vertical = QVBoxLayout() p1_vertical.setContentsMargins(0, 0, 0, 0) p1_vertical.addWidget(toolbar) p1_vertical.addWidget(self.annotationList) self.manager.setLayout(p1_vertical) self.dock.setWidget(self.manager) self.dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dock) self.rb = QgsRubberBand(self.iface.mapCanvas(), QGis.Polygon) self.annotations = [] self.annotationsName = [] def checkItem(self, item): row = self.annotationList.row(item) self.annotationsName[row] = item.text() if item.checkState() == Qt.Checked: self.annotations[row].show() else: self.annotations[row].hide() if item.isSelected(): item.setSelected(False) self.rb.reset() def selectAnnotation(self): index = self.annotationList.currentRow() self.rb.reset() self.rb.setColor(QColor(0, 0, 255, 128)) mapTool = QgsMapTool(self.iface.mapCanvas()) point = self.annotations[index].pos().toPoint() pt1 = mapTool.toMapCoordinates(QPoint(point.x() - 10, point.y() - 10)) pt2 = mapTool.toMapCoordinates(QPoint(point.x() + 10, point.y() + 10)) rect = QgsRectangle(pt1, pt2) poly = QgsGeometry().fromRect(rect) self.rb.setToGeometry(poly, None) def unload(self): del self.dock def tr(self, message): return QCoreApplication.translate('AnnotationManager', message) def getAnnotations(self): annotations = [] items = self.iface.mapCanvas().items() for item in items: if item.data(0) == 'AnnotationItem': annotations.append(item) return annotations def refreshAnnotations(self): for annotation in self.getAnnotations(): if annotation not in self.annotations: self.annotations.append(annotation) self.annotationsName.append('Annotation') i = 0 to_del = [] for annotation in self.annotations: if annotation not in self.getAnnotations(): to_del.append(i) i += 1 i = 0 for index in to_del: self.annotations.pop(index) self.annotationsName.pop(index) self.annotationList.clearSelection() self.annotationList.clear() # argh for annotation in self.annotations: item = QListWidgetItem(self.annotationsName[i]) if annotation.isVisible(): item.setCheckState(Qt.Checked) else: item.setCheckState(Qt.Unchecked) item.setFlags(item.flags() | Qt.ItemIsEditable) self.annotationList.addItem(item) i += 1 # fin argh def removeAnnotation(self): if len(self.annotationList.selectedItems()) > 0: index = self.annotationList.currentRow() self.annotationList.takeItem(index) self.annotationList.clearSelection() self.annotationList.clearFocus() self.iface.mapCanvas().scene().removeItem(self.annotations[index]) self.annotations.pop(index) self.annotationsName.pop(index) self.rb.reset() def projectOpen(self): del self.annotations[:] del self.annotationsName[:] self.refreshAnnotations() def initGui(self): self.refreshAnnotations()
class RRepositoryBrowser(QDialog): def __init__(self, pipe, parent=None): QDialog.__init__(self, parent) mirror = robjects.r.getOption('repos') contrib_url = robjects.r.get('contrib.url', mode='function') available_packages = robjects.r.get('available.packages', mode='function') self.setWindowTitle("manageR - Install R Packages") self.setWindowIcon(QIcon(":icon")) p = available_packages() self.pipe = pipe self.names = QStringList(p.rownames) self.parent = parent self.packageList = QListWidget(self) self.packageList.setAlternatingRowColors(True) self.packageList.setEditTriggers(QAbstractItemView.NoEditTriggers) self.packageList.setSortingEnabled(True) self.packageList.setSelectionMode(QAbstractItemView.ExtendedSelection) self.packageList.setToolTip("Select packages to install") self.packageList.setWhatsThis("List of packages available on CRAN") self.packageList.insertItems(0, self.names) self.dependCheckbox = QCheckBox(self) self.dependCheckbox.setText("Install all dependencies") self.dependCheckbox.setChecked(True) self.closeCheckbox = QCheckBox(self) self.closeCheckbox.setText("Close dialog on completion") self.closeCheckbox.setChecked(False) filterEdit = QLineEdit(self) filterLabel = QLabel("Filter packages", self) self.outputEdit = QTextEdit(self) self.outputEdit.setReadOnly(True) self.outputEdit.setVisible(False) self.buttonBox = QDialogButtonBox(QDialogButtonBox.Apply|QDialogButtonBox.Close) self.buttonBox.addButton("Details >>", QDialogButtonBox.ActionRole) vbox = QVBoxLayout(self) hbox = QHBoxLayout() hbox.addWidget(filterLabel) hbox.addWidget(filterEdit) vbox.addLayout(hbox) vbox.addWidget(self.dependCheckbox) vbox.addWidget(self.packageList) vbox.addWidget(self.closeCheckbox) vbox.addWidget(self.outputEdit) vbox.addWidget(self.buttonBox) self.started = False self.setMinimumSize(80,50) self.connect(filterEdit, SIGNAL("textChanged(QString)"), self.filterPackages) #self.connect(self.buttonBox, SIGNAL("rejected()"), self.reject) self.connect(self.buttonBox, SIGNAL("clicked(QAbstractButton*)"), self.buttonClicked) def buttonClicked(self, button): if button.text() == "Details >>": self.showDetails() button.setText("Details <<") elif button.text() == "Details <<": self.hideDetails() button.setText("Details >>") if not self.started: if self.buttonBox.standardButton(button) == QDialogButtonBox.Apply: self.installPackages() else: self.reject() def showDetails(self): self.outputEdit.setVisible(True) def hideDetails(self): self.outputEdit.setVisible(False) def filterPackages(self, text): self.packageList.clear() self.packageList.insertItems(0, self.names.filter(QRegExp(r"^%s" % text))) firstItem = self.packageList.item(0) if firstItem.text().startsWith(text): self.packageList.setCurrentItem(firstItem) # else: # self.packageList.clearSelection() def currentPackages(self): return [unicode(item.text()) for item in self.packageList.selectedItems()] def installPackages(self): pkgs = self.currentPackages() count = len(pkgs) if count < 1: QMessageBox.warning(self, "manageR - Warning", "Please choose at least one valid package") return False pkgs = QStringList(pkgs).join("','") checked = self.dependCheckbox.isChecked() if checked: depends = "TRUE" else: depends = "FALSE" self.pipe.send("install.packages(c('%s'), dependencies=%s, repos=%s)" % (pkgs, depends, robjects.r.getOption("repos"))) self.started = True self.startTimer(30) return True def timerEvent(self, e): if self.started: try: output = self.pipe.recv() if output is None: self.started=False self.killTimer(e.timerId()) else: self.printOutput(output) except EOFError: pass QApplication.processEvents() def printOutput(self, output): self.outputEdit.insertPlainText(output) self.outputEdit.ensureCursorVisible()
class HistoryWidget(QWidget): currentTrackChanged = pyqtSignal(dict) def __init__(self, bbclient, config, parent=None): super(HistoryWidget, self).__init__(parent) self.bbclient = bbclient self.config = config self.track_list = [] self.list = QListWidget(self) self.list.setUniformItemSizes(True) self.list.setSelectionMode(QListWidget.ExtendedSelection) self.list.currentRowChanged.connect(self._onRowChanged) self.delete_btn = QPushButton(QIcon(resource_path('img/delete.png')), '', self) self.save_btn = QPushButton(QIcon(resource_path('img/save.png')), '', self) self.upload_btn = QPushButton(QIcon(resource_path('img/upload.png')), '', self) for i, w in enumerate((self.delete_btn, self.save_btn, self.upload_btn)): w.setIconSize(QSize(22, 22)) if i < 1: w.setMinimumSize(32, 32) w.setMaximumSize(32, 32) else: w.setMinimumSize(58, 32) w.setMaximumSize(58, 32) save_menu = QMenu('Export tracks', self) act = save_menu.addAction('Save as TCX') act.triggered.connect(self._onSaveAsTCX) act = save_menu.addAction('Save as BDX (Bryton GPX extension)') act.triggered.connect(self._onSaveAsBDX) self.save_btn.setMenu(save_menu) upload_menu = QMenu('Upload tracks', self) act = upload_menu.addAction(QIcon(resource_path('img/strava-icon.png')), 'Upload to Strava.com') act.triggered.connect(self._onUploadStrava) act = upload_menu.addAction(QIcon(resource_path('img/bryton-icon.png')), 'Upload to Brytonsport.com') act.triggered.connect(self._onUploadBrytonSport) self.upload_btn.setMenu(upload_menu) self.delete_btn.clicked.connect(self._onDeleteTracks) self._createLayout() self.message_overlay = MessageWidget(self) self.message_overlay.setLoading('Loading tracklist') bbclient.refreshingTrackList.connect(self.message_overlay.show) def setTrackList(self, track_list, device_info): self.list.clear() self.device_info = device_info self.track_list = track_list for track in track_list: item = QListWidgetItem(track['name']) item.setData(TRACK_ITEM_ROLE, track['id']) self.list.addItem(item) self.message_overlay.hide() def resizeEvent(self, event): self.message_overlay.resize(event.size()) super(HistoryWidget, self).resizeEvent(event) def _onDeleteTracks(self): tracks = self._getSelectedTracks() if not tracks: tracks = self.track_list ids = map(lambda t: t['id'], tracks) names = map(lambda t: t['name'], tracks) msg = 'Are you sure you want to delete the following {} track(s):'.format(len(tracks)) msg += '\n' + '\n'.join(names) res = QMessageBox.question(self, 'Delete tracks?', msg, QMessageBox.Ok | QMessageBox.Cancel, QMessageBox.Cancel) print res if res == QMessageBox.Ok: print ids # self.bbclient._refreshTrackList() d = ProgressDialog('Finalizing', "Don't close this window\n(It may stall for a little while on 93%)", self) d.progress.setRange(0, 100) d.resize(250, 80) self.bbclient.finalizingProgress.connect(d.progress.setValue) self.bbclient.tracksDeleted.connect(d.accept) def _onFail(): QMessageBox.warning(self, 'Delete failed') d.accept() self.bbclient.deleteFailed.connect(_onFail) self.bbclient.deleteTracks(ids) d.exec_() def _onUploadStrava(self): tracks = self._getSelectedTracks() if not tracks: tracks = self.track_list strava.upload_to_strava(tracks, self.device_info, self, auth_token=self.config.get('strava_auth_token'), password=self.config.get('strava_password'), username=self.config.get('strava_email')) def _onUploadBrytonSport(self): brytonsport.upload_to_brytonsport(self.bbclient, self, username=self.config.get('bryton_email'), password=self.config.get('bryton_password'), session_id=self.config.get('bryton_session_id')) def _onSaveAsTCX(self): tracks = self._getSelectedTracks() if not tracks: tracks = self.track_list # QMessageBox.information(self, 'No tracks selected', 'You need to select the tracks you want to save.') if not tracks: return if len(tracks) == 1: name = QFileDialog.getSaveFileName(self, 'Save file %s' % tracks[0]['name'], self._trackFilename(tracks[0]['name'], 'tcx'), filter='TCX (*.tcx)') if name: self._saveContent(name, tcx.bryton_gpx_to_tcx(tracks[0]['gpx'], pretty=True, device=self.device_info)) else: dir = QFileDialog.getExistingDirectory(self, 'Open Directory', '', QFileDialog.ShowDirsOnly) if not dir: return for t in tracks: name = path.join(str(dir), self._trackFilename(t['name'], 'tcx')) self._saveContent(name, tcx.bryton_gpx_to_tcx(t['gpx'], pretty=True, device=self.device_info)) def _onSaveAsBDX(self): tracks = self._getSelectedTracks() if not tracks: tracks = self.track_list if not tracks: return if len(tracks) == 1: name = QFileDialog.getSaveFileName(self, 'Save file %s' % tracks[0]['name'], self._trackFilename(tracks[0]['name'], 'bdx'), filter='BDX (*.bdx)') if name: self._saveContent(name, tracks[0]['gpx'].toString(pretty=True)) else: dir = QFileDialog.getExistingDirectory(self, 'Open Directory', '', QFileDialog.ShowDirsOnly) if not dir: return for t in tracks: name = path.join(str(dir), self._trackFilename(t['name'], 'gpx')) self._saveContent(name, t['gpx'].toString(pretty=True)) def _saveContent(self, filename, content): with open(filename, 'w') as f: f.write(content) def _trackFilename(self, name, ext): return name.replace('/', '').replace(' ', '-').replace(':', '') + '.' + ext def _getSelectedTracks(self): items = self.list.selectedItems() tracks = [] for item in items: index = self.list.row(item) tracks.append(self.track_list[index]) return tracks def _onRowChanged(self, row): track = self.track_list[row] self.currentTrackChanged.emit(track) def _createLayout(self): l = QVBoxLayout() l.addWidget(self.list) h = QHBoxLayout() h.addWidget(self.delete_btn) h.addStretch() h.addWidget(self.save_btn) h.addWidget(self.upload_btn) l.addLayout(h) self.setLayout(l)
class InputListParameterWidget(GenericParameterWidget): """Widget class for List parameter.""" def __init__(self, parameter, parent=None): """Constructor .. versionadded:: 2.2 :param parameter: A ListParameter object. :type parameter: InputListParameter """ super(InputListParameterWidget, self).__init__(parameter, parent) # value cache for self._parameter.value # copy the list so the original is unaffected self._value_cache = list(self._parameter.value) self._input = QListWidget() self._input.setSelectionMode(QAbstractItemView.SingleSelection) if self._parameter.maximum_item_count != \ self._parameter.minimum_item_count: tool_tip = 'Select between %d and %d items' % ( self._parameter.minimum_item_count, self._parameter.maximum_item_count) else: tool_tip = 'Select exactly %d items' % ( self._parameter.maximum_item_count) self._input.setToolTip(tool_tip) # arrange widget self._insert_item_input = QLineEdit() vbox_layout = QVBoxLayout() hbox_layout = QHBoxLayout() self._input_add_button = QPushButton('Add') self._input_remove_button = QPushButton('Remove') # arrange line edit, add button, remove button in horizontal layout hbox_layout.addWidget(self._insert_item_input) hbox_layout.addWidget(self._input_add_button) hbox_layout.addWidget(self._input_remove_button) # arrange vertical layout vbox_layout.addLayout(hbox_layout) vbox_layout.addWidget(self._input) self._inner_input_layout.addLayout(vbox_layout) # override self._input_layout arrangement to make the label at the top # reset the layout self._input_layout.setParent(None) self._help_layout.setParent(None) self._label.setParent(None) self._inner_input_layout.setParent(None) self._input_layout = QVBoxLayout() self._input_layout.setSpacing(0) # put element into layout self._input_layout.addWidget(self._label) self._input_layout.addLayout(self._inner_input_layout) self._main_layout.addLayout(self._input_layout) self._main_layout.addLayout(self._help_layout) # connect handler # noinspection PyUnresolvedReferences self._input_add_button.clicked.connect(self.on_add_button_click) # noinspection PyUnresolvedReferences self._input_remove_button.clicked.connect(self.on_remove_button_click) # noinspection PyUnresolvedReferences self._insert_item_input.returnPressed.connect( self._input_add_button.click) # noinspection PyUnresolvedReferences self._input.itemChanged.connect(self.on_row_changed) self.refresh_list() # init row add error handler self._add_row_error_handler = None @property def add_row_error_handler(self): """return error handler if user mistakenly add row of unexpected type :return: a function handler :rtype: () -> None """ return self._add_row_error_handler @add_row_error_handler.setter def add_row_error_handler(self, value): """Set error handler to handle user mistakenly add row of unexpected type """ self._add_row_error_handler = value def refresh_list(self): self._input.clear() if not self._parameter.ordering == InputListParameter.NotOrdered: self._value_cache.sort() if self._parameter.ordering == InputListParameter.DescendingOrder: self._value_cache.reverse() for opt in self._value_cache: item = QListWidgetItem() item.setText(str(opt)) item.setFlags(item.flags() | Qt.ItemIsEditable) self._input.addItem(item) def on_add_button_click(self): try: value = self._parameter.element_type( self._insert_item_input.text()) self._value_cache.append(value) self.refresh_list() except ValueError: err = self.raise_invalid_type_exception() if self.add_row_error_handler is not None: self.add_row_error_handler(err) else: raise err def on_remove_button_click(self): for opt in self._input.selectedItems(): index = self._input.indexFromItem(opt) del self._value_cache[index.row()] self.refresh_list() def on_row_changed(self, item): try: index = self._input.indexFromItem(item).row() prev_value = self._value_cache[index] self._value_cache[index] = self._parameter.element_type( item.text()) self.refresh_list() except ValueError: item.setText(str(prev_value)) self.raise_invalid_type_exception() def raise_invalid_type_exception(self): message = 'Expecting element type of %s' % ( self._parameter.element_type.__name__) err = ValueError(message) return err def get_parameter(self): """Obtain list parameter object from the current widget state. :returns: A ListParameter from the current state of widget """ try: self._parameter.value = self._value_cache except ValueError: err = self.raise_invalid_type_exception() raise err return self._parameter
class SeriesPreview(QDialog): def __init__(self, parent=None): super(SeriesPreview, self).__init__(parent) self.data = None self.workingSet = None self.list = QListWidget() self.cancel = QPushButton('Close') self.apply = QPushButton('Update') self.layout = QGridLayout() self.layout.addWidget(self.list, 0, 0, 1, 2) self.layout.addWidget(self.apply, 1, 0) self.layout.addWidget(self.cancel, 1, 1) self.setLayout(self.layout) self.initComponents() self.initActions() def initComponents(self): self.setWindowFlags(Qt.Tool) self.setWindowTitle("Time series") self.setStyleSheet('''QPushButton { color: #333; border: 1px solid #555; border-radius: 11px; padding: 2px; background: qradialgradient(cx: 0.3, cy: -0.4, fx: 0.3, fy: -0.4, radius: 1.35, stop: 0 #fff, stop: 1 #888); min-width: 80px; } QPushButton:hover { color: #fff; background: qradialgradient(cx: 0.3, cy: -0.4, fx: 0.3, fy: -0.4, radius: 1.35, stop: 0 #fff, stop: 1 #bbb);} QPushButton:pressed { background: qradialgradient(cx: 0.4, cy: -0.1, fx: 0.4, fy: -0.1, radius: 1.35, stop: 0 #fff, stop: 1 #ddd);} QPushButton:checked { background: qradialgradient(cx: 0.4, cy: -0.1, fx: 0.4, fy: -0.1, radius: 1.35, stop: 0 #fff, stop: 1 #ddd);} QListView::focus { border: 2px solid black; border-radius: 6px; } QScrollBar:vertical { width: 20px; border: 1px solid grey; border-radius: 6px; background-color: transparent; margin: 28px 0 28px 0; } QScrollBar::add-line:vertical { background: transparent; height: 32px; subcontrol-position: bottom; subcontrol-origin: margin; } QScrollBar::sub-line:vertical { background: transparent; height: 32px; subcontrol-position: top; subcontrol-origin: margin; } QScrollBar::up-arrow:vertical { width: 20px; height: 32px; background: transparent; image: url(../res/icons/arrow_up.png); } QScrollBar::up-arrow:hover { bottom: 2px; } QScrollBar::down-arrow:vertical { width: 20px; height: 32px; background: transparent; image: url(../res/icons/arrow_down.png); } QScrollBar::down-arrow:hover { top: 2px; } QScrollBar::handle:vertical { border-radius: 6px; background: url(../res/icons/handle.png) 0% center no-repeat; background-color: white; min-height: 32px; } QScrollBar::handle:hover { background: url(../res/icons/handle_hover.png) 0% center no-repeat; background-color: white; border: 1px solid gray; }''') self.list.setAlternatingRowColors(True) self.list.setStyleSheet('''QListView::item:selected:active { background: qlineargradient(x1: 1, y1: 0, x2: 0, y2: 3, stop: 0 #cbdaf1, stop: 1 #bfcde4); } QListView::item { border: 1px solid #d9d9d9; border-top-color: transparent; border-bottom-color: transparent; } QListView::item:hover { background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #e7effd, stop: 1 #cbdaf1); border: 1px solid #bfcde4; }''') self.list.setSelectionMode(QAbstractItemView.ExtendedSelection) self.list.setContextMenuPolicy(Qt.ActionsContextMenu) def initActions(self): self.apply.clicked.connect(self.applyChanges) self.cancel.clicked.connect(self.close) self.list.itemDoubleClicked.connect(self.removeFromList) self.list.addAction(QAction('&Remove selected', self, triggered=self.removeItems)) #--- actions ---# def updateData(self, data): self.data = data self.workingSet = data[0][:] self.updateList() def updateList(self): self.list.clear() for item in self.workingSet: item = QListWidgetItem(str(item)) item.setTextAlignment(Qt.AlignCenter) self.list.addItem(item) def applyChanges(self): self.data = (self.workingSet, self.data[1]) def removeFromList(self, item): self.workingSet.remove(float(item.text())) self.list.takeItem(self.list.indexFromItem(item).row()) def removeItems(self): for item in self.list.selectedItems(): self.workingSet.remove(float(item.text())) self.list.takeItem(self.list.indexFromItem(item).row())
class DoubleListWidget(QWidget): __pyqtSignals__ = ('stateChanged') def __init__(self, parent, list, active_list): QWidget.__init__(self, parent) self.list = list self.list_active = active_list self.item_list = {} layout = QHBoxLayout(self) self.setLayout(layout) self.layout = layout self.addActiveListView() self.addButtons() self.addInactiveListView() self.fillListView() def addButtons(self): frame = QFrame(self) layout_v = QVBoxLayout(frame) frame.setLayout(layout_v) button_left = QPushButton('<- Left') self.connect(button_left, SIGNAL('clicked()'), lambda: self.MoveToActive()) layout_v.addWidget(button_left) button_right = QPushButton('Right ->') self.connect(button_right, SIGNAL('clicked()'), lambda: self.MoveToInactive()) layout_v.addWidget(button_right) layout_v.addStretch(100) self.layout.addWidget(frame) def addActiveListView(self): self.listview_active = QListWidget(self) self.listview_active.setSelectionMode(QAbstractItemView.ExtendedSelection) self.layout.addWidget(self.listview_active) def addInactiveListView(self): self.listview_inactive = QListWidget(self) self.listview_inactive.setSelectionMode(QAbstractItemView.ExtendedSelection) self.layout.addWidget(self.listview_inactive) def fillListView(self): self.listview_active.clear() self.listview_inactive.clear() for i in self.list_active: self.listview_active.addItem(i) for i in self.list: if not i in self.list_active: self.listview_inactive.addItem(i) self.listview_inactive.sortItems() self.listview_active.sortItems() def MoveToActive(self): for i in self.listview_inactive.selectedItems(): self.list_active.append(i.text()) self.fillListView() self.emit(SIGNAL("stateChanged")) def MoveToInactive(self): for i in self.listview_active.selectedItems(): self.list_active.remove(i.text()) self.fillListView() self.emit(SIGNAL("stateChanged")) def getActiveList(self): return self.list_active
class CAT(QSplitter, Script): def __init__(self): Script.__init__(self, "cat") self.vfs = vfs.vfs() self.type = "cat" self.icon = None self.currentCodec = "UTF-8" def start(self, args): self.args = args try: self.node = args["file"].value() except: pass def g_display(self): QSplitter.__init__(self) self.offsets = self.linecount() self.initShape() self.read(0) def initShape(self): self.hbox = QHBoxLayout() self.hbox.setContentsMargins(0, 0, 0, 0) self.listWidget = QListWidget() self.listWidget.setSortingEnabled(True) for codec in QTextCodec.availableCodecs(): self.listWidget.addItem(str(codec)) item = self.listWidget.findItems('UTF-8', Qt.MatchExactly)[0] self.listWidget.setCurrentItem(item) self.listWidget.scrollToItem(item) textAreaWidget = QWidget() self.hbox.addWidget(self.listWidget) self.connect(self.listWidget, SIGNAL("itemSelectionChanged()"), self.codecChanged) self.scroll = Scroll(self) self.text = TextEdit(self) self.hbox.addWidget(self.text) self.hbox.addWidget(self.scroll) textAreaWidget.setLayout(self.hbox) self.addWidget(self.listWidget) self.addWidget(textAreaWidget) self.setStretchFactor(0, 0) self.setStretchFactor(1, 1) def codecChanged(self): self.currentCodec = self.listWidget.selectedItems()[0].text() self.read(self.scroll.value()) def read(self, line): self.vfile = self.node.open() padd = 0 if line > padd: padd = 1 self.vfile.seek(self.offsets[line] + padd) self.text.clear() codec = QTextCodec.codecForName(self.currentCodec) decoder = codec.makeDecoder() self.text.textCursor().insertText( decoder.toUnicode(self.vfile.read(1024 * 10))) self.text.moveCursor(QTextCursor.Start) self.vfile.close() def linecount(self): offsets = [0] self.vfile = self.node.open() offsets.extend(self.vfile.indexes('\n')) self.vfile.close() self.lines = len(offsets) return offsets def updateWidget(self): pass def c_display(self): file = self.node.open() fsize = self.node.size() size = 0 self.buff = "" while size < fsize: try: tmp = file.read(4096) except vfsError, e: print self.buff break if len(tmp) == 0: print tmp break size += len(tmp) self.buff += tmp print tmp file.close() if len(self.buff): return self.buff
class TagsDialog(QDialog): def __init__(self, dockwidget, parent, params): QDialog.__init__(self, parent) main_lay = QVBoxLayout(self) self.dockwidget = dockwidget self.params = params self.setWindowTitle('Tags editor') # Top frame self.fra_top = QFrame() fra_top_lay = QVBoxLayout(self.fra_top) self.lst_main = QListWidget(self) self.btn_add = QPushButton('Add tag') self.btn_add.clicked.connect(self.add_tag) self.btn_remove = QPushButton('Remove tag') self.btn_remove.clicked.connect(self.remove_tag) fra_top_lay.addWidget(self.lst_main) fra_top_lay.addWidget(self.btn_add) fra_top_lay.addWidget(self.btn_remove) # Bottom frame self.fra_bottom = QFrame() fra_bottom_lay = QHBoxLayout(self.fra_bottom) btb_main = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) btb_main.accepted.connect(self.ok) btb_main.rejected.connect(self.reject) fra_bottom_lay.addWidget(btb_main) # Main main_lay.addWidget(self.fra_top) main_lay.addWidget(self.fra_bottom) self.initialize() def initialize(self): for tag_name in self.params.tag_names: self.lst_main.insertItem(self.lst_main.count(), QListWidgetItem(tag_name, self.lst_main)) def ok(self): tag_names = [] for r in range(self.lst_main.count()): tag_names.append(self.lst_main.item(r).text()) self.params.tag_names = tag_names self.setVisible(False) def reject(self): self.setVisible(False) def add_tag(self): tag_name_dialog = TagNameDialog(self.dockwidget, self) tag_name_dialog.exec_() tag_name = tag_name_dialog.get_tag_name() if tag_name is not None: current_row = self.lst_main.currentRow() if current_row is None: current_row = self.lst_main.count() self.lst_main.insertItem(current_row, QListWidgetItem(tag_name, self.lst_main)) def remove_tag(self): sel_items = self.lst_main.selectedItems() for sel_item in sel_items: self.lst_main.takeItem(self.lst_main.row(sel_item))
class CheckList(HelpedWidget): def __init__(self, model, label="", help_link=""): HelpedWidget.__init__(self, "", help_link) layout = QVBoxLayout() widget = QWidget() widget.setLayout(layout) self.checkAllButton = QToolButton() self.checkAllButton.setIcon(resourceIcon("checked")) self.checkAllButton.setIconSize(QSize(16, 16)) self.checkAllButton.setToolButtonStyle(Qt.ToolButtonIconOnly) self.checkAllButton.setAutoRaise(True) self.checkAllButton.setToolTip("Select all") self.uncheckAllButton = QToolButton() self.uncheckAllButton.setIcon(resourceIcon("notchecked")) self.uncheckAllButton.setIconSize(QSize(16, 16)) self.uncheckAllButton.setToolButtonStyle(Qt.ToolButtonIconOnly) self.uncheckAllButton.setAutoRaise(True) self.uncheckAllButton.setToolTip("Unselect all") self.list = QListWidget() self.list.setContextMenuPolicy(Qt.CustomContextMenu) self.list.setSelectionMode(QAbstractItemView.ExtendedSelection) self.search_box = SearchBox() check_button_layout = QHBoxLayout() check_button_layout.setMargin(0) check_button_layout.setSpacing(0) check_button_layout.addWidget(QLabel(label)) check_button_layout.addStretch(1) check_button_layout.addWidget(self.checkAllButton) check_button_layout.addWidget(self.uncheckAllButton) layout.addLayout(check_button_layout) layout.addWidget(self.list) layout.addWidget(self.search_box) self.addWidget(widget) self.connect(self.checkAllButton, SIGNAL('clicked()'), self.checkAll) self.connect(self.uncheckAllButton, SIGNAL('clicked()'), self.uncheckAll) self.connect(self.list, SIGNAL('itemChanged(QListWidgetItem*)'), self.itemChanged) self.search_box.filterChanged.connect(self.filterList) # self.connect(self.search_box, SIGNAL('filterChanged(str)'), self.filterList) self.connect(self.list, SIGNAL('customContextMenuRequested(QPoint)'), self.showContextMenu) assert isinstance(model, (SelectableModelMixin, ListModelMixin)) self.model = model self.model.observable().attach(SelectableModelMixin.SELECTION_CHANGED_EVENT, self.modelChanged) self.model.observable().attach(ListModelMixin.LIST_CHANGED_EVENT, self.modelChanged) self.modelChanged() def itemChanged(self, item): """@type item: QListWidgetItem""" if item.checkState() == Qt.Checked: self.model.selectValue(str(item.text())) elif item.checkState() == Qt.Unchecked: self.model.unselectValue(str(item.text())) else: raise AssertionError("Unhandled checkstate!") def modelChanged(self): self.list.clear() items = self.model.getList() for item in items: list_item = QListWidgetItem(item) list_item.setFlags(list_item.flags() | Qt.ItemIsUserCheckable) if self.model.isValueSelected(item): list_item.setCheckState(Qt.Checked) else: list_item.setCheckState(Qt.Unchecked) self.list.addItem(list_item) self.filterList(self.search_box.filter()) def setSelectionEnabled(self, enabled): self.setEnabled(enabled) self.checkAllButton.setEnabled(enabled) self.uncheckAllButton.setEnabled(enabled) def filterList(self, filter): filter = filter.lower() for index in range(0, self.list.count()): item = self.list.item(index) text = str(item.text()).lower() if filter == "": item.setHidden(False) elif filter in text: item.setHidden(False) else: item.setHidden(True) def checkAll(self): self.model.selectAll() def uncheckAll(self): self.model.unselectAll() def checkSelected(self): items = [] for item in self.list.selectedItems(): items.append(str(item.text())) for item in items: self.model.selectValue(item) def uncheckSelected(self): items = [] for item in self.list.selectedItems(): items.append(str(item.text())) for item in items: self.model.unselectValue(item) def showContextMenu(self, point): p = self.list.mapToGlobal(point) menu = QMenu() check_selected = menu.addAction("Check selected") uncheck_selected = menu.addAction("Uncheck selected") menu.addSeparator() clear_selection = menu.addAction("Clear selection") selected_item = menu.exec_(p) if selected_item == check_selected: self.checkSelected() elif selected_item == uncheck_selected: self.uncheckSelected() elif selected_item == clear_selection: self.list.clearSelection()
class CheckList(HelpedWidget): def __init__(self, model, label="", help_link=""): HelpedWidget.__init__(self, "", help_link) layout = QVBoxLayout() widget = QWidget() widget.setLayout(layout) self.checkAllButton = QToolButton() self.checkAllButton.setIcon(resourceIcon("checked")) self.checkAllButton.setIconSize(QSize(16, 16)) self.checkAllButton.setToolButtonStyle(Qt.ToolButtonIconOnly) self.checkAllButton.setAutoRaise(True) self.checkAllButton.setToolTip("Select all") self.uncheckAllButton = QToolButton() self.uncheckAllButton.setIcon(resourceIcon("notchecked")) self.uncheckAllButton.setIconSize(QSize(16, 16)) self.uncheckAllButton.setToolButtonStyle(Qt.ToolButtonIconOnly) self.uncheckAllButton.setAutoRaise(True) self.uncheckAllButton.setToolTip("Unselect all") self.list = QListWidget() self.list.setContextMenuPolicy(Qt.CustomContextMenu) self.list.setSelectionMode(QAbstractItemView.ExtendedSelection) self.search_box = SearchBox() check_button_layout = QHBoxLayout() check_button_layout.setMargin(0) check_button_layout.setSpacing(0) check_button_layout.addWidget(QLabel(label)) check_button_layout.addStretch(1) check_button_layout.addWidget(self.checkAllButton) check_button_layout.addWidget(self.uncheckAllButton) layout.addLayout(check_button_layout) layout.addWidget(self.list) layout.addWidget(self.search_box) self.addWidget(widget) self.connect(self.checkAllButton, SIGNAL('clicked()'), self.checkAll) self.connect(self.uncheckAllButton, SIGNAL('clicked()'), self.uncheckAll) self.connect(self.list, SIGNAL('itemChanged(QListWidgetItem*)'), self.itemChanged) self.search_box.filterChanged.connect(self.filterList) # self.connect(self.search_box, SIGNAL('filterChanged(str)'), self.filterList) self.connect(self.list, SIGNAL('customContextMenuRequested(QPoint)'), self.showContextMenu) assert isinstance(model, (SelectableModelMixin, ListModelMixin)) self.model = model self.model.observable().attach( SelectableModelMixin.SELECTION_CHANGED_EVENT, self.modelChanged) self.model.observable().attach(ListModelMixin.LIST_CHANGED_EVENT, self.modelChanged) self.modelChanged() def itemChanged(self, item): """@type item: QListWidgetItem""" if item.checkState() == Qt.Checked: self.model.selectValue(str(item.text())) elif item.checkState() == Qt.Unchecked: self.model.unselectValue(str(item.text())) else: raise AssertionError("Unhandled checkstate!") def modelChanged(self): self.list.clear() items = self.model.getList() for item in items: list_item = QListWidgetItem(item) list_item.setFlags(list_item.flags() | Qt.ItemIsUserCheckable) if self.model.isValueSelected(item): list_item.setCheckState(Qt.Checked) else: list_item.setCheckState(Qt.Unchecked) self.list.addItem(list_item) self.filterList(self.search_box.filter()) def setSelectionEnabled(self, enabled): self.setEnabled(enabled) self.checkAllButton.setEnabled(enabled) self.uncheckAllButton.setEnabled(enabled) def filterList(self, filter): filter = filter.lower() for index in range(0, self.list.count()): item = self.list.item(index) text = str(item.text()).lower() if filter == "": item.setHidden(False) elif filter in text: item.setHidden(False) else: item.setHidden(True) def checkAll(self): self.model.selectAll() def uncheckAll(self): self.model.unselectAll() def checkSelected(self): items = [] for item in self.list.selectedItems(): items.append(str(item.text())) for item in items: self.model.selectValue(item) def uncheckSelected(self): items = [] for item in self.list.selectedItems(): items.append(str(item.text())) for item in items: self.model.unselectValue(item) def showContextMenu(self, point): p = self.list.mapToGlobal(point) menu = QMenu() check_selected = menu.addAction("Check selected") uncheck_selected = menu.addAction("Uncheck selected") menu.addSeparator() clear_selection = menu.addAction("Clear selection") selected_item = menu.exec_(p) if selected_item == check_selected: self.checkSelected() elif selected_item == uncheck_selected: self.uncheckSelected() elif selected_item == clear_selection: self.list.clearSelection()
class CheckList(QWidget): def __init__(self, model, label="", help_link="", custom_filter_button=None): """ :param custom_filter_button: if needed, add a button that opens a custom filter menu. Useful when search alone isn't enough to filter the list. :type custom_filter_button: QToolButton """ QWidget.__init__(self) self._model = model if help_link != "": addHelpToWidget(self, help_link) layout = QVBoxLayout() self._createCheckButtons() self._list = QListWidget() self._list.setContextMenuPolicy(Qt.CustomContextMenu) self._list.setSelectionMode(QAbstractItemView.ExtendedSelection) self._search_box = SearchBox() check_button_layout = QHBoxLayout() check_button_layout.setMargin(0) check_button_layout.setSpacing(0) check_button_layout.addWidget(QLabel(label)) check_button_layout.addStretch(1) check_button_layout.addWidget(self._checkAllButton) check_button_layout.addWidget(self._uncheckAllButton) layout.addLayout(check_button_layout) layout.addWidget(self._list) """ Inserts the custom filter button, if provided. The caller is responsible for all related actions. """ if custom_filter_button is not None: search_bar_layout = QHBoxLayout() search_bar_layout.addWidget(self._search_box) search_bar_layout.addWidget(custom_filter_button) layout.addLayout(search_bar_layout) else: layout.addWidget(self._search_box) self.setLayout(layout) self._checkAllButton.clicked.connect(self.checkAll) self._uncheckAllButton.clicked.connect(self.uncheckAll) self._list.itemChanged.connect(self.itemChanged) self._search_box.filterChanged.connect(self.filterList) self._list.customContextMenuRequested.connect(self.showContextMenu) self._model.selectionChanged.connect(self.modelChanged) self._model.modelChanged.connect(self.modelChanged) self.modelChanged() def _createCheckButtons(self): self._checkAllButton = QToolButton() self._checkAllButton.setIcon(resourceIcon("checked")) self._checkAllButton.setIconSize(QSize(16, 16)) self._checkAllButton.setToolButtonStyle(Qt.ToolButtonIconOnly) self._checkAllButton.setAutoRaise(True) self._checkAllButton.setToolTip("Select all") self._uncheckAllButton = QToolButton() self._uncheckAllButton.setIcon(resourceIcon("notchecked")) self._uncheckAllButton.setIconSize(QSize(16, 16)) self._uncheckAllButton.setToolButtonStyle(Qt.ToolButtonIconOnly) self._uncheckAllButton.setAutoRaise(True) self._uncheckAllButton.setToolTip("Unselect all") def itemChanged(self, item): """@type item: QListWidgetItem""" if item.checkState() == Qt.Checked: self._model.selectValue(str(item.text())) elif item.checkState() == Qt.Unchecked: self._model.unselectValue(str(item.text())) else: raise AssertionError("Unhandled checkstate!") def modelChanged(self): self._list.clear() items = self._model.getList() for item in items: list_item = QListWidgetItem(item) list_item.setFlags(list_item.flags() | Qt.ItemIsUserCheckable) if self._model.isValueSelected(item): list_item.setCheckState(Qt.Checked) else: list_item.setCheckState(Qt.Unchecked) self._list.addItem(list_item) self.filterList(self._search_box.filter()) def setSelectionEnabled(self, enabled): self.setEnabled(enabled) self._checkAllButton.setEnabled(enabled) self._uncheckAllButton.setEnabled(enabled) def filterList(self, filter): filter = filter.lower() for index in range(0, self._list.count()): item = self._list.item(index) text = str(item.text()).lower() if filter == "": item.setHidden(False) elif filter in text: item.setHidden(False) else: item.setHidden(True) def checkAll(self): """ Checks all visible items in the list. """ for index in range(0, self._list.count()): item = self._list.item(index) if not item.isHidden(): self._model.selectValue(str(item.text())) def uncheckAll(self): """ Unchecks all items in the list, visible or not """ self._model.unselectAll() def checkSelected(self): items = [] for item in self._list.selectedItems(): items.append(str(item.text())) for item in items: self._model.selectValue(item) def uncheckSelected(self): items = [] for item in self._list.selectedItems(): items.append(str(item.text())) for item in items: self._model.unselectValue(item) def showContextMenu(self, point): p = self._list.mapToGlobal(point) menu = QMenu() check_selected = menu.addAction("Check selected") uncheck_selected = menu.addAction("Uncheck selected") menu.addSeparator() clear_selection = menu.addAction("Clear selection") selected_item = menu.exec_(p) if selected_item == check_selected: self.checkSelected() elif selected_item == uncheck_selected: self.uncheckSelected() elif selected_item == clear_selection: self._list.clearSelection()
class CAT(QSplitter, Script): def __init__(self): Script.__init__(self, "cat") self.vfs = vfs.vfs() self.type = "cat" self.icon = None self.currentCodec = "UTF-8" def start(self, args): self.args = args try: self.node = args["file"].value() except: pass def g_display(self): QSplitter.__init__(self) self.offsets = self.linecount() self.initShape() self.read(0) def initShape(self): self.hbox = QHBoxLayout() self.hbox.setContentsMargins(0, 0, 0, 0) self.listWidget = QListWidget() self.listWidget.setSortingEnabled(True) for codec in QTextCodec.availableCodecs(): self.listWidget.addItem(str(codec)) item = self.listWidget.findItems('UTF-8', Qt.MatchExactly)[0] self.listWidget.setCurrentItem(item) self.listWidget.scrollToItem(item) textAreaWidget = QWidget() self.hbox.addWidget(self.listWidget) self.connect(self.listWidget, SIGNAL("itemSelectionChanged()"), self.codecChanged) self.scroll = Scroll(self) self.text = TextEdit(self) self.hbox.addWidget(self.text) self.hbox.addWidget(self.scroll) textAreaWidget.setLayout(self.hbox) self.addWidget(self.listWidget) self.addWidget(textAreaWidget) self.setStretchFactor(0, 0) self.setStretchFactor(1, 1) def codecChanged(self): self.currentCodec = self.listWidget.selectedItems()[0].text() self.read(self.scroll.value()) def read(self, line): self.vfile = self.node.open() padd = 0 if line > padd: padd = 1 self.vfile.seek(self.offsets[line]+padd) self.text.clear() codec = QTextCodec.codecForName(self.currentCodec) decoder = codec.makeDecoder() self.text.textCursor().insertText(decoder.toUnicode(self.vfile.read(1024*10))) self.text.moveCursor(QTextCursor.Start) self.vfile.close() def linecount(self): offsets = [0] self.vfile = self.node.open() offsets.extend(self.vfile.indexes('\n')) self.vfile.close() self.lines = len(offsets) return offsets def updateWidget(self): pass def c_display(self): file = self.node.open() fsize = self.node.size() size = 0 self.buff = "" while size < fsize: try: tmp = file.read(4096) except vfsError, e: print self.buff break if len(tmp) == 0: print tmp break size += len(tmp) self.buff += tmp print tmp file.close() if len(self.buff): return self.buff
class Dialogo(QDialog): def __init__(self, archivos, principal): super(Dialogo, self).__init__(principal) self.setWindowTitle(self.tr("Archivos sin guardar!")) self.principal = principal self.evento_ignorado = False vLayout = QVBoxLayout(self) label = QLabel(self.tr("Algunos archivos no se han guardado, " "selecciona los que \ndeseas guardar:")) vLayout.addWidget(label) hLayout = QHBoxLayout() self.lista = QListWidget() [self.lista.addItem(item) for item in archivos] self.lista.setSelectionMode(QAbstractItemView.ExtendedSelection) hLayout.addWidget(self.lista) layoutBotones = QVBoxLayout() botonTodo = QPushButton(self.tr("Todo")) botonNinguno = QPushButton(self.tr("Ninguno")) botonGuardar = QPushButton(self.tr("Guardar")) botonCancelar = QPushButton(self.tr("Cancelar")) botonNoGuardar = QPushButton(self.tr("No guardar")) layoutBotones.addWidget(botonTodo) layoutBotones.addWidget(botonNinguno) layoutBotones.addWidget(botonGuardar) layoutBotones.addWidget(botonNoGuardar) layoutBotones.addWidget(botonCancelar) hLayout.addLayout(layoutBotones) vLayout.addLayout(hLayout) self.tecla_escape = QShortcut(QKeySequence(Qt.Key_Escape), self) self.connect(self.tecla_escape, SIGNAL("activated()"), self.ignorar) self.connect(botonTodo, SIGNAL("clicked()"), self.seleccionar_todo) self.connect(botonNinguno, SIGNAL("clicked()"), self.deseleccionar) self.connect(botonGuardar, SIGNAL("clicked()"), self.guardar) self.connect(botonNoGuardar, SIGNAL("clicked()"), self.close) self.connect(botonCancelar, SIGNAL("clicked()"), self.ignorar) def ignorar(self): self.evento_ignorado = True self.hide() def ignorado(self): return self.evento_ignorado def seleccionar_todo(self): for item in range(self.lista.count()): self.lista.item(item).setSelected(True) def deseleccionar(self): for item in range(self.lista.count()): self.lista.item(item).setSelected(False) def guardar(self): archivos_seleccionados = self.lista.selectedItems() for archivo in archivos_seleccionados: nombre = archivo.text() self.principal.guardar_seleccionado(nombre) self.close()
class ListParameterWidget(GenericParameterWidget): """Widget class for List parameter.""" def __init__(self, parameter, parent=None): """Constructor .. versionadded:: 2.2 :param parameter: A ListParameter object. :type parameter: ListParameter """ super(ListParameterWidget, self).__init__(parameter, parent) self._input = QListWidget() self._input.setSelectionMode(QAbstractItemView.MultiSelection) if self._parameter.maximum_item_count != \ self._parameter.minimum_item_count: tool_tip = 'Select between %d and %d items' % ( self._parameter.minimum_item_count, self._parameter.maximum_item_count) else: tool_tip = 'Select exactly %d items' % ( self._parameter.maximum_item_count) self._input.setToolTip(tool_tip) for opt in self._parameter.options_list: item = QListWidgetItem() item.setFlags(item.flags() | Qt.ItemIsEditable) item.setText(str(opt)) self._input.addItem(item) if opt in self._parameter.value: item.setSelected(True) self.inner_input_layout.addWidget(self._input) # override self._input_layout arrangement to make the label at the top # reset the layout self.input_layout.setParent(None) self.help_layout.setParent(None) self.label.setParent(None) self.inner_input_layout.setParent(None) self.input_layout = QVBoxLayout() self.input_layout.setSpacing(0) # put element into layout self.input_layout.addWidget(self.label) self.input_layout.addLayout(self.inner_input_layout) self.main_layout.addLayout(self.input_layout) self.main_layout.addLayout(self.help_layout) def raise_invalid_type_exception(self): message = 'Expecting element type of %s' % ( self._parameter.element_type.__name__) err = ValueError(message) return err def get_parameter(self): """Obtain list parameter object from the current widget state. :returns: A ListParameter from the current state of widget """ selected_value = [] for opt in self._input.selectedItems(): index = self._input.indexFromItem(opt) selected_value.append(self._parameter.options_list[index.row()]) try: self._parameter.value = selected_value except ValueError: err = self.raise_invalid_type_exception() raise err return self._parameter
class multipleListWidget(QWidget): def __init__(self, parent, typeid, predefs, editable): QWidget.__init__(self) self.parent = parent self.typeid = typeid self.editable = editable self.predefs = predefs self.init() def init(self): self.vbox = QVBoxLayout() self.vbox.setSpacing(5) self.vbox.setMargin(0) self.createHeader() self.valuelist = QListWidget() self.vbox.addWidget(self.valuelist) self.setLayout(self.vbox) def createHeader(self): self.whead = QWidget() self.headerlayout = QHBoxLayout() self.headerlayout.setSpacing(0) self.headerlayout.setMargin(0) if self.typeid in (typeId.Node, typeId.Path) and self.editable: self.addPath() else: self.addSingleArgument() self.addButton = QPushButton(QIcon(":add.png"), "") self.rmButton = QPushButton(QIcon(":del_dump.png"), "") self.addButton.setIconSize(QSize(16, 16)) self.rmButton.setIconSize(QSize(16, 16)) self.connect(self.addButton, SIGNAL("clicked()"), self.addParameter) self.connect(self.rmButton, SIGNAL("clicked()"), self.rmParameter) self.connect(self.addButton, SIGNAL("clicked()"), self.parent.argumentChanged) self.connect(self.rmButton, SIGNAL("clicked()"), self.parent.argumentChanged) self.headerlayout.addWidget(self.addButton, 0) self.headerlayout.addWidget(self.rmButton, 0) self.whead.setLayout(self.headerlayout) self.vbox.addWidget(self.whead) def addParameterConfig(self, config): try : if len(config) : for item in config: self.valuelist.insertItem(self.valuelist.count() + 1, item) except TypeError: self.valuelist.insertItem(self.valuelist.count() + 1, config) def addParameter(self): if isinstance(self.container, QComboBox): item = self.container.currentText() else: item = self.container.text() if len(self.valuelist.findItems(item, Qt.MatchExactly)) == 0: self.valuelist.insertItem(self.valuelist.count() + 1, item) def rmParameter(self): selected = self.valuelist.selectedItems() for item in selected: row = self.valuelist.row(item) self.valuelist.takeItem(row) def addSingleArgument(self): if len(self.predefs) > 0: self.container = QComboBox() for value in self.predefs: if self.typeid == typeId.Node: self.container.addItem(value.value().name()) else: self.container.addItem(value.toString()) self.container.setEditable(self.editable) else: self.container = QLineEdit() self.container.setReadOnly(self.editable) self.headerlayout.addWidget(self.container, 2) def addPath(self): if len(self.predefs) > 0: self.container = QComboBox() self.container.setReadOnly(False) for value in self.predefs: self.container.addItem(value.toString()) else: self.container = QLineEdit() self.container.setReadOnly(False) if self.typeid == typeId.Path: browse = addLocalPathButton(self, key, self.container, isdir=False) else: browse = addLocalPathButton(self, key, self.container, isdir=False, nodetype=True) self.headerlayout.addWidget(self.container, 2) self.headerlayout.addWidget(browse, 0) def addPredefValue(self): selected = self.predefs.selectedItems() for item in selected: self.valuelist.insertItem(self.valuelist.count() + 1, item.text())
class ListParameterWidget(GenericParameterWidget): """Widget class for List parameter.""" def __init__(self, parameter, parent=None): """Constructor .. versionadded:: 2.2 :param parameter: A ListParameter object. :type parameter: ListParameter """ super(ListParameterWidget, self).__init__(parameter, parent) self._input = QListWidget() self._input.setSelectionMode(QAbstractItemView.MultiSelection) if self._parameter.maximum_item_count != \ self._parameter.minimum_item_count: tool_tip = 'Select between %d and %d items' % ( self._parameter.minimum_item_count, self._parameter.maximum_item_count) else: tool_tip = 'Select exactly %d items' % ( self._parameter.maximum_item_count) self._input.setToolTip(tool_tip) for opt in self._parameter.options_list: item = QListWidgetItem() item.setFlags(item.flags() | Qt.ItemIsEditable) item.setText(str(opt)) self._input.addItem(item) if opt in self._parameter.value: item.setSelected(True) self._inner_input_layout.addWidget(self._input) # override self._input_layout arrangement to make the label at the top # reset the layout self._input_layout.setParent(None) self._help_layout.setParent(None) self._label.setParent(None) self._inner_input_layout.setParent(None) self._input_layout = QVBoxLayout() self._input_layout.setSpacing(0) # put element into layout self._input_layout.addWidget(self._label) self._input_layout.addLayout(self._inner_input_layout) self._main_layout.addLayout(self._input_layout) self._main_layout.addLayout(self._help_layout) def raise_invalid_type_exception(self): message = 'Expecting element type of %s' % ( self._parameter.element_type.__name__) err = ValueError(message) return err def get_parameter(self): """Obtain list parameter object from the current widget state. :returns: A ListParameter from the current state of widget """ selected_value = [] for opt in self._input.selectedItems(): index = self._input.indexFromItem(opt) selected_value.append(self._parameter.options_list[index.row()]) try: self._parameter.value = selected_value except ValueError: err = self.raise_invalid_type_exception() raise err return self._parameter
class RunsDialog(QtHelper.EnhancedQDialog): """ Runs several dialog """ RefreshRepository = pyqtSignal(str) def __init__(self, dialogName, parent = None, iRepo=None, lRepo=None, rRepo=None): """ Constructor """ QtHelper.EnhancedQDialog.__init__(self, parent) self.name = self.tr("Prepare a group of runs") self.projectReady = False self.iRepo = iRepo self.lRepo = lRepo self.rRepo = rRepo self.createDialog() self.createConnections() def createDialog(self): """ Create qt dialog """ self.setWindowTitle( self.name ) mainLayout = QHBoxLayout() layoutTests = QHBoxLayout() layoutRepoTest = QVBoxLayout() self.prjCombo = QComboBox(self) self.prjCombo.setEnabled(False) self.repoTests = QTreeWidget(self) self.repoTests.setFrameShape(QFrame.NoFrame) if USE_PYQT5: self.repoTests.header().setSectionResizeMode(QHeaderView.Stretch) else: self.repoTests.header().setResizeMode(QHeaderView.Stretch) self.repoTests.setHeaderHidden(True) self.repoTests.setContextMenuPolicy(Qt.CustomContextMenu) self.repoTests.setIndentation(10) layoutRepoTest.addWidget(self.prjCombo) layoutRepoTest.addWidget(self.repoTests) self.testsList = QListWidget(self) layoutTests.addLayout( layoutRepoTest ) layoutTests.addWidget( self.testsList ) mainLayout.addLayout( layoutTests ) buttonLayout = QVBoxLayout() self.okButton = QPushButton(self.tr("Execute All"), self) self.okButton.setEnabled(False) self.cancelButton = QPushButton(self.tr("Cancel"), self) self.upButton = QPushButton(self.tr("UP"), self) self.upButton.setEnabled(False) self.downButton = QPushButton(self.tr("DOWN"), self) self.downButton.setEnabled(False) self.clearButton = QPushButton(self.tr("Remove All"), self) self.delButton = QPushButton(self.tr("Remove"), self) self.delButton.setEnabled(False) self.runSimultaneous = QCheckBox(self.tr("Simultaneous Run")) self.schedImmed = QRadioButton(self.tr("Run Immediately")) self.schedImmed.setChecked(True) self.schedAt = QRadioButton(self.tr("Run At:")) self.schedAtDateTimeEdit = QDateTimeEdit(QDateTime.currentDateTime()) self.schedAtDateTimeEdit.setEnabled(False) buttonLayout.addWidget(self.okButton) buttonLayout.addWidget(self.runSimultaneous) buttonLayout.addWidget(self.schedImmed) buttonLayout.addWidget(self.schedAt) buttonLayout.addWidget(self.schedAtDateTimeEdit) buttonLayout.addWidget( self.upButton ) buttonLayout.addWidget( self.downButton ) buttonLayout.addWidget( self.delButton ) buttonLayout.addWidget( self.clearButton ) buttonLayout.addWidget(self.cancelButton) mainLayout.addLayout(buttonLayout) self.setMinimumHeight(400) self.setMinimumWidth(750) self.setLayout(mainLayout) def initProjects(self, projects=[], defaultProject=1): """ Initialize projects """ # init date and time self.schedAtDateTimeEdit.setDateTime(QDateTime.currentDateTime()) self.projectReady = False self.repoTests.clear() self.prjCombo.clear() self.testsList.clear() self.prjCombo.setEnabled(True) # insert data pname = '' for p in projects: self.prjCombo.addItem ( p['name'] ) if defaultProject == p['project_id']: pname = p['name'] for i in xrange(self.prjCombo.count()): item_text = self.prjCombo.itemText(i) if str(pname) == str(item_text): self.prjCombo.setCurrentIndex(i) self.projectReady = True self.RefreshRepository.emit(pname) def initializeTests(self, listing): """ Initialize tests """ self.repoTests.clear() self.testRoot = self.rRepo.Item(repo = self.iRepo.remote(), parent = self.repoTests, txt = "Root", type = QTreeWidgetItem.UserType+10, isRoot = True ) self.testRoot.setSelected(True) self.createRepository(listing=listing, parent=self.testRoot,fileincluded=True) self.repoTests.sortItems(0, Qt.AscendingOrder) self.hideItems(hideTsx=False, hideTpx=False, hideTcx=True, hideTdx=True, hideTxt=True, hidePy=True, hideTux=False, hidePng=True, hideTgx=False, hideTax=False) def createRepository(self, listing, parent, fileincluded=True): """ Create repository @param listing: @type listing: list @param parent: @type parent: @param fileincluded: @type fileincluded: boolean """ try: for dct in listing: if dct["type"] == "folder": item = self.rRepo.Item(repo = self.iRepo.remote(), parent = parent, txt = dct["name"], propertiesFile=dct ) self.createRepository( dct["content"] , item, fileincluded ) else: if fileincluded: if dct["type"] == "file": pname = self.iRepo.remote().getProjectName(dct["project"]) # {'modification': 1342259500, 'type': 'file', 'name': '__init__.py', 'size': '562 } item = self.rRepo.Item(repo = self.iRepo.remote(), parent = parent, txt = dct["name"] , propertiesFile=dct, type = QTreeWidgetItem.UserType+0, projectId=dct["project"], projectName=pname ) except Exception as e: self.error( "unable to create tree for runs: %s" % e ) def onProjectChanged(self, projectItem): """ Called when the project changed on the combo box """ if self.projectReady: item_text = self.prjCombo.itemText(projectItem) self.RefreshRepository.emit(item_text) def createConnections (self): """ create qt connections * ok * cancel """ self.prjCombo.currentIndexChanged.connect(self.onProjectChanged) self.okButton.clicked.connect( self.acceptClicked ) self.cancelButton.clicked.connect( self.reject ) self.upButton.clicked.connect(self.upTest) self.downButton.clicked.connect(self.downTest) self.clearButton.clicked.connect(self.clearList) self.delButton.clicked.connect(self.delTest) self.testsList.itemClicked.connect(self.onItemSelected) self.testsList.itemSelectionChanged.connect(self.onItemSelectionChanged) self.schedAt.toggled.connect(self.onSchedAtActivated) self.repoTests.itemDoubleClicked.connect( self.onTestDoucleClicked ) def onSchedAtActivated(self, toggled): """ On sched at button activated """ if toggled: self.schedAtDateTimeEdit.setEnabled(True) else: self.schedAtDateTimeEdit.setEnabled(False) def onItemSelectionChanged(self): """ Called on item selection changed """ self.onItemSelected(itm=None) def onItemSelected(self, itm): """ Call on item selected """ selectedItems = self.testsList.selectedItems() if len(selectedItems): self.delButton.setEnabled(True) self.upButton.setEnabled(True) self.downButton.setEnabled(True) else: self.delButton.setEnabled(False) self.upButton.setEnabled(False) self.downButton.setEnabled(False) if not self.testsList.count(): self.okButton.setEnabled(False) def upTest(self): """ Up test """ currentRow = self.testsList.currentRow() currentItem = self.testsList.takeItem(currentRow) self.testsList.insertItem(currentRow - 1, currentItem) def downTest(self): """ Down test """ currentRow = self.testsList.currentRow() currentItem = self.testsList.takeItem(currentRow) self.testsList.insertItem(currentRow + 1, currentItem) def delTest(self): """ Del test """ currentRow = self.testsList.currentRow() currentItem = self.testsList.takeItem(currentRow) def clearList(self): """ Clear test """ self.testsList.clear() self.delButton.setEnabled(False) self.upButton.setEnabled(False) self.downButton.setEnabled(False) self.okButton.setEnabled(False) def iterateTree(self, item, hideTsx, hideTpx, hideTcx, hideTdx, hideTxt, hidePy, hideTux, hidePng, hideTgx, hideTax): """ Iterate tree """ child_count = item.childCount() for i in range(child_count): subitem = item.child(i) subchild_count = subitem.childCount() if subchild_count > 0: self.iterateTree(item=subitem, hideTsx=hideTsx, hideTpx=hideTpx, hideTcx=hideTcx, hideTdx=hideTdx, hideTxt=hideTxt, hidePy=hidePy, hideTux=hideTux, hidePng=hidePng, hideTgx=hideTgx, hideTax=hideTax) else: if hideTux and subitem.getExtension() == self.rRepo.EXTENSION_TUX: subitem.setHidden (True) elif hideTpx and subitem.getExtension() == self.rRepo.EXTENSION_TPX: subitem.setHidden (True) elif hideTgx and subitem.getExtension() == self.rRepo.EXTENSION_TGX: subitem.setHidden (True) elif hideTcx and subitem.getExtension() == self.rRepo.EXTENSION_TCX: subitem.setHidden (True) elif hideTsx and subitem.getExtension() == self.rRepo.EXTENSION_TSX: subitem.setHidden (True) elif hideTdx and subitem.getExtension() == self.rRepo.EXTENSION_TDX: subitem.setHidden (True) elif hideTxt and subitem.getExtension() == self.rRepo.EXTENSION_TXT: subitem.setHidden (True) elif hidePy and subitem.getExtension() == self.rRepo.EXTENSION_PY: subitem.setHidden (True) elif hidePng and subitem.getExtension() == self.rRepo.EXTENSION_PNG: subitem.setHidden (True) elif hideTax and subitem.getExtension() == self.rRepo.EXTENSION_TAx: subitem.setHidden (True) else: subitem.setHidden(False) def hideItems(self, hideTsx=False, hideTpx=False, hideTcx=False, hideTdx=False, hideTxt=False, hidePy=False, hideTux=False, hidePng=False, hideTgx=False, hideTax=False): """ Hide items """ root = self.repoTests.invisibleRootItem() self.iterateTree(item=root, hideTsx=hideTsx, hideTpx=hideTpx, hideTcx=hideTcx, hideTdx=hideTdx, hideTxt=hideTxt, hidePy=hidePy, hideTux=hideTux, hidePng=hidePng, hideTgx=hideTgx, hideTax=hideTax) def onTestDoucleClicked(self, testItem): """ On tests double clicked """ if testItem.type() != QTreeWidgetItem.UserType+0: return self.okButton.setEnabled(True) currentProject = self.prjCombo.currentText() testName = "%s:%s" % (str(currentProject),testItem.getPath(withFileName = True)) testItem = QListWidgetItem(testName ) if testName.endswith(self.rRepo.EXTENSION_TUX): testItem.setIcon(QIcon(":/tux.png")) if testName.endswith(self.rRepo.EXTENSION_TSX): testItem.setIcon(QIcon(":/tsx.png")) if testName.endswith(self.rRepo.EXTENSION_TPX): testItem.setIcon(QIcon(":/tpx.png")) if testName.endswith(self.rRepo.EXTENSION_TGX): testItem.setIcon(QIcon(":/tgx.png")) if testName.endswith(self.rRepo.EXTENSION_TAX): testItem.setIcon(QIcon(":/tax.png")) self.testsList.addItem( testItem ) def acceptClicked (self): """ Called on accept button """ self.accept() def getTests(self): """ Returns all tests in the list """ tests = [] for i in xrange(self.testsList.count()): testItem = self.testsList.item(i) tests.append( str(testItem.text()) ) runSimultaneous = False if self.runSimultaneous.isChecked(): runSimultaneous = True if self.schedImmed.isChecked(): runAt = (0,0,0,0,0,0) return (tests, False, runAt, runSimultaneous) else: pydt = self.schedAtDateTimeEdit.dateTime().toPyDateTime() runAt = (pydt.year, pydt.month, pydt.day, pydt.hour, pydt.minute, pydt.second) return (tests, True, runAt, runSimultaneous)
class FileArgs(QtHelper.EnhancedQDialog, Logger.ClassLogger): """ File arguments dialog """ def __init__(self, dataArgs, parent=None): """ Dialog to fill arguments for the file probe @param dataArgs: @type dataArgs: @param parent: @type parent: """ super(FileArgs, self).__init__(parent) self.dataArgs = dataArgs self.createDialog() self.createConnections() self.loadDefaultData() def createDialog(self): """ Create qt dialog """ mainLayout = QHBoxLayout() dataLayout = QVBoxLayout() self.labelHelp = QLabel("Path of the file to retrieve:") self.lineEdit = QLineEdit() self.listBox = QListWidget() dataLayout.addWidget(self.labelHelp) dataLayout.addWidget(self.lineEdit) dataLayout.addWidget(self.listBox) buttonLayout = QVBoxLayout() self.addButton = QPushButton("Add", self) self.delButton = QPushButton("Remove", self) self.delButton.setEnabled(False) self.editButton = QPushButton("Edit", self) self.editButton.setEnabled(False) self.clearButton = QPushButton("Clear", self) self.okButton = QPushButton("Ok", self) self.cancelButton = QPushButton("Cancel", self) buttonLayout.addWidget(self.addButton) buttonLayout.addWidget(self.delButton) buttonLayout.addWidget(self.editButton) buttonLayout.addWidget(self.clearButton) buttonLayout.addWidget(self.okButton) buttonLayout.addWidget(self.cancelButton) mainLayout.addLayout(dataLayout) mainLayout.addLayout(buttonLayout) self.setLayout(mainLayout) self.setWindowTitle("File Probe > Arguments") def createConnections(self): """ Create qt connections """ self.okButton.clicked.connect(self.accept) self.cancelButton.clicked.connect(self.reject) self.addButton.clicked.connect(self.addItem) self.delButton.clicked.connect(self.delItem) self.editButton.clicked.connect(self.editItem) self.clearButton.clicked.connect(self.clearList) self.listBox.itemClicked.connect(self.onItemSelected) def clearList(self): """ Clear the list """ self.listBox.clear() def onItemSelected(self, itm): """ Called when an item is selected """ self.delButton.setEnabled(True) self.editButton.setEnabled(True) def editItem(self): """ Edit the selected item """ self.delButton.setEnabled(False) self.editButton.setEnabled(False) # retrieve value to put it in the line edit and then remove item model = self.listBox.model() for selectedItem in self.listBox.selectedItems(): qIndex = self.listBox.indexFromItem(selectedItem) if sys.version_info > (3, ): self.lineEdit.setText(model.data(qIndex)) else: self.lineEdit.setText(model.data(qIndex).toString()) model.removeRow(qIndex.row()) def delItem(self): """ Delete the selected item """ self.delButton.setEnabled(False) self.editButton.setEnabled(False) # remove item model = self.listBox.model() for selectedItem in self.listBox.selectedItems(): qIndex = self.listBox.indexFromItem(selectedItem) model.removeRow(qIndex.row()) def addItem(self): """ Add item """ txt = self.lineEdit.text() if txt != '': self.listBox.insertItem(0, txt) self.lineEdit.setText('') def loadDefaultData(self): """ Load the default data """ try: if len(self.dataArgs) == 0: return dat = eval(self.dataArgs) if 'files' in dat: list_files = dat['files'] self.listBox.insertItems(0, list_files) except Exception as e: self.error(e) def getArgs(self): """ Returns arguments Examples: {'files': [ '/etc/init.d/ntpd', '/root/wmi-1.3.14-2.el5.art.x86_64.rpm' ] } """ listFiles = [] model = self.listBox.model() # iterate all items in a QListWidget for index in xrange(self.listBox.count()): itm = self.listBox.item(index) qIndex = self.listBox.indexFromItem(itm) if sys.version_info > (3, ): listFiles.append(model.data(qIndex)) else: listFiles.append(str(model.data(qIndex).toString())) ret = {'files': listFiles} if len(listFiles) == 0: ret = '' return str(ret)
class ChainComposerDialog(QDialog): def __init__(self, parent=None): super(ChainComposerDialog, self).__init__(parent) self.setWindowTitle('Composer Chain') layout = QVBoxLayout() mainLayout = QHBoxLayout() selectionLayout = QVBoxLayout() label = QLabel('Available Filters:') selectionLayout.addWidget(label) self.__selectionList = QListWidget() selectionLayout.addWidget(self.__selectionList) mainLayout.addLayout(selectionLayout) actionsLayout = QVBoxLayout() actionsLayout.addStretch() addButton = QPushButton('Add>>') addButton.clicked.connect(self.__handleAdd) actionsLayout.addWidget(addButton) removeButton = QPushButton('Remove') actionsLayout.addWidget(removeButton) removeAllButton = QPushButton('Remove All') actionsLayout.addWidget(removeAllButton) actionsLayout.addStretch() mainLayout.addLayout(actionsLayout) chainLayout = QVBoxLayout() chainLayout.addWidget(QLabel('Chain:')) self.__chainList = QListWidget() chainLayout.addWidget(self.__chainList) mainLayout.addLayout(chainLayout) layout.addLayout(mainLayout) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.okClick) buttonBox.rejected.connect(self.cancelClick) layout.addWidget(buttonBox) # buttonLayout = QHBoxLayout() # okButton = QPushButton('OK') # okButton.clicked.connect(self.accept) # buttonLayout.addWidget(okButton) # cancelButton = QPushButton('Cancel') # cancelButton.clicked.connect(self.reject) # buttonLayout.addWidget(cancelButton) # layout.addLayout(buttonLayout) self.setLayout(layout) self.__composer = None def okClick(self): print "OK!" self.accept() def cancelClick(self): print "Cancel" self.reject() def setComposer(self, composer): self.__composer = composer @property def selectionList(self): return self.__getStrings(self.__selectionList) @selectionList.setter def setSelectionList(self, filters): for i in xrange(self.__selectionList.count()): self.__selectionList.takeItem(i) self.__selectionList.addItems(filters) def filterAt(self, row): return self.__selectionList.item(row).text() def addToChain(self, filterName): self.__chainList.addItem(filterName) @property def composedFilter(self): return self.__getStrings(self.__chainList) @staticmethod def __getStrings(listWidget): return tuple(listWidget.item(i) for i in range(listWidget.count())) def __handleAdd(self): if self.__composer is None: return for item in self.__selectionList.selectedItems(): row = self.__selectionList.row(item) self.__composer.add(row)
class LoginListWindow(QDialog): class _Dialog(QDialog): def __init__(self,parent=None): super(QDialog,self).__init__(parent) self.value='' self.edit=QLineEdit() self.layout=QHBoxLayout(self) self.button_layout=QVBoxLayout() self.setWindowTitle(u"输入名字") self.ok_button=QPushButton(u"确定") self.cancel_button=QPushButton(u"取消") self.layout.addWidget(self.edit) self.layout.addLayout(self.button_layout) self.button_layout.addWidget(self.ok_button) self.button_layout.addWidget(self.cancel_button) QObject.connect(self.ok_button,SIGNAL("clicked()"),self.ok) QObject.connect(self.cancel_button,SIGNAL("clicked()"),self.close) def ok(self): self.value=unicode(self.edit.text()) self.close() def getvalue(self,value): self.value=value self.edit.setText(value) self.exec_() return self.value class _Item(QListWidgetItem): def __init__(self,name,url,cookiefile=None,parent=None): super(QListWidgetItem,self).__init__(name,parent) #~ super(QObject,self).__init__(parent) self.loggedin=False #~ print name,cookiefile self.cookiefile=cookiefile=name+".cookies" if cookiefile is None else cookiefile self.name=name self.cookiejar=None self.view=LoginWindow(url,cookiefile) self.view.setWindowTitle(u"登录:"+name) self.dialog=LoginListWindow._Dialog(parent) self.show_msg=pyqtSlot(unicode,unicode) #~ self.connect(self,SIGNAL("show_msg(unicode,unicode)"),self,SLOT("showMessage(unicode,unicode)")) def login(self): #~ print True #~ self.emit(SIGNAL("send_msg"),u"logging") self.showLogging() #~ print self.cookiefile cj=check_login(self.cookiefile) if cj is None: cj=self.view.login() uname=get_username_by_cookiejar(cj,ignore=True) if uname: self.showSecceeded("%s<%s>"%(self.name,uname)) #~ self.emit(SIGNAL("send_msg"),u"succeeded",u"%s<%s>"%(self.name,uname)) self.loggedin=True self.cookiejat=cj return cj else: self.showFailed() #~ self.emit(SIGNAL("send_msg"),u"failed") return None def editName(self): self.name=self.dialog.getvalue(self.name) self.setText(self.name) return self.name def editCookies(self): self.cookiejar=self.view.login() return self.cookiejar @pyqtSlot(unicode,unicode) def showMessage(self,type_,name): print type_ { 'logging':self.showLogging, 'secceeded':self.showSecceeded, 'failed':self.showFailed, }[type_](name) def showLogging(self,name=None): self.setText((name if name is not None else self.name)+u"[登录中]") self.setTextColor(QColor("yellow")) def showSecceeded(self,name=None): self.setText((name if name is not None else self.name)+u"[成功]") self.setTextColor(QColor("green")) def showFailed(self,name=None): self.setText((name if name is not None else self.name)+u"[失败]") self.setTextColor(QColor("red")) class _Thread(QThread): def __init__(self,func,*args,**kwargs): self.func=func self.args=args self.kwargs=kwargs super(QThread,self).__init__(None) def run(self): self.func(*self.args,**self.kwargs) def __init__(self,url,dirpath=None,parent=None): super(QDialog,self).__init__(parent) if dirpath is not None and not os.path.exists(dirpath):os.mkdir(dirpath) self.url=url self.progress_dialog=QProgressDialog() self.progress_dialog.setWindowTitle(u"登录中") self.progress_dialog.setLabelText(u"登录中") self.loading_dialog=QDialog(self) self.dirpath=dirpath self.list=QListWidget() self.layout=QHBoxLayout(self) self.button_layout=QVBoxLayout() self.layout.addWidget(self.list) self.layout.addLayout(self.button_layout) self.add_button=QPushButton(u"添加") self.edit_name_button=QPushButton(u"设置名字") self.edit_cookies_button=QPushButton(u"设置Cookies") self.delete_button=QPushButton(u"删除") self.refresh_button=QPushButton(u"刷新") self.button_layout.addWidget(self.add_button) self.button_layout.addWidget(self.delete_button) self.button_layout.addWidget(self.refresh_button) self.button_layout.addWidget(self.edit_name_button) self.button_layout.addWidget(self.edit_cookies_button) QObject.connect(self.add_button,SIGNAL("clicked()"),self._add) QObject.connect(self.edit_name_button,SIGNAL("clicked()"),self.edit_name) QObject.connect(self.edit_cookies_button,SIGNAL("clicked()"),self.edit_cookies) QObject.connect(self.delete_button,SIGNAL("clicked()"),self._delete) QObject.connect(self.refresh_button,SIGNAL("clicked()"),self.login) #~ self.load() def edit_name(self): return [i.editName() for i in self.list.selectedItems()] def edit_cookies(self): return [i.editCookies() for i in self.list.selectedItems()] def login(self): return [self.list.item(i).login() for i in self.progress_iter(range(self.list.count()),u"登录")] def _add(self): self.add(self._Dialog(self).getvalue(unicode(self.list.count())),login=True) def _delete(self): i=self.list.currentRow() item=self.list.takeItem(i) if os.path.exists(item.cookiefile): os.remove(item.cookiefile) def add(self,name,cookiefile=None,login=False): item=LoginListWindow._Item(name,self.url,('' if self.dirpath is None else self.dirpath+os.sep)+name+".cookies" if cookiefile is None else cookiefile) self.list.addItem(item) if login: item.login() def load(self,list_=None,dir_=None): dir_=self.dirpath if dir_ is None else dir_ list_=os.listdir(dir_) if list_ is None else list_ for f in self.progress_iter(list_,u'载入文件'): p=dir_+os.sep+f+".cookies" n=os.path.splitext(f)[0] self.add(n,p) self.login() #~ print list(self) def load_from_yaml(self,yaml_file,dir_=None): dt=yaml.load(open(yaml_file)) self.load(dt["usernames"],dt["dir"]) def load_asynchronously(self,dir_=None): self.thread=self._Thread(self.load,dir_) #~ print True self.thread.start() def progress_iter(self,list_,title=u'更新中'): len_=len(list_) self.loading_dialog.setWindowTitle(title) self.progress_dialog.setWindowTitle(title) self.progress_dialog.setLabelText(title) self.progress_dialog.setMaximum(len_) self.progress_dialog.show() #~ self.loading_dialog.show() #~ self.loading_dialog.close() for i in xrange(len_): self.progress_dialog.setValue(i+1) self.progress_dialog.show() #~ print i,'/',len_ yield list_[i] self.progress_dialog.close() def load_and_show(self,list_=None,dir_=None): self.load(list_,dir_) self.show() def __iter__(self): return ( re.search(r"^(.+?)(<.*>)?(\[.*\])?$",unicode(self.list.item(i).text())).group(1) for i in range(self.list.count()))