class ArrayWidget(QWidget, NodeWidget): data_type = "Array" two_rows = True data_class = ArrayNode def __init__(self, name, data, scheme, parent=None): QWidget.__init__(self, parent) NodeWidget.__init__(self, name, data, scheme) self.layout = QVBoxLayout(self) self.layout.setMargin(0) self.layout.setContentsMargins(0,0,0,0) self._listwidget = QListWidget(self) self.layout.addWidget(self._listwidget) hlayout = QHBoxLayout() self.layout.addLayout(hlayout) self._plus_minus_widget = PlusMinusWidget(self.create_item, self.delete_item, self) hlayout.addWidget(self._plus_minus_widget) self.element_scheme = self.scheme["ElementScheme"] self.new_data = NodeWidget.get_default_data(self.element_scheme, self.data) hlayout.addStretch(1) self.add_widget = NodeWidget.create_node_widget("__not_exist", self.new_data, self.element_scheme) hlayout.addWidget(self.add_widget) def delete_item(self): row = self._listwidget.row(self._listwidget.currentItem()) new_data = list(self.data.get()) del new_data[row] self.data.set(tuple(new_data)) def create_item(self): self.data.set(list(self.data.get())+[Node.create_node(self.new_data.get()),]) def __createItem(self, itemname): item = QListWidgetItem(itemname) # item.setFlags (Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled ) self._listwidget.addItem(item) def dump(self): pass def load(self): self._listwidget.clear() for item in self.data.get(): self.__createItem(unicode(item)) @classmethod def _get_default_data(cls, scheme, data): return ArrayNode([])
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 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 Navegador(custom_dock.CustomDock): def __init__(self): custom_dock.CustomDock.__init__(self) self.navegador = QListWidget() self.setWidget(self.navegador) self.navegador.itemClicked.connect(self._cambiar_editor) EDIS.cargar_lateral("navegador", self) def agregar(self, archivo): self.navegador.addItem(archivo) def eliminar(self, indice): self.navegador.takeItem(indice) def cambiar_foco(self, indice): self.navegador.setCurrentRow(indice) def _cambiar_editor(self): indice = self.navegador.row(self.navegador.currentItem()) principal = EDIS.componente("principal") principal.cambiar_widget(indice)
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 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 AbstractStructuredWidget(QWidget, NodeWidget): data_type = None two_rows = True data_class = None def __init__(self, name, data, scheme, parent=None): QWidget.__init__(self, parent) NodeWidget.__init__(self, name, data, scheme) self.layout = QVBoxLayout(self) self.layout.setMargin(0) self._listwidget = QListWidget(self) self.layout.addWidget(self._listwidget) hlayout = QHBoxLayout() self.layout.setMargin(0) self.layout.setContentsMargins(0,0,0,0) self.layout.addLayout(hlayout) self._plus_minus_widget = PlusMinusWidget(self.create_item, self.delete_item, self) hlayout.addWidget(self._plus_minus_widget) # self._edit_button = SmallSquareButton("edit", self) # hlayout.addWidget(self._edit_button) # self._edit_button.clicked.connect(self.edit_item) self._listwidget.itemDoubleClicked.connect(self.edit_item) hlayout.addStretch(1) self._listwidget.setEditTriggers(QAbstractItemView.EditKeyPressed) self._listwidget.itemChanged.connect(self.rename_item) self._listwidget.currentItemChanged.connect(self.current_item_changed) self.current_item_index = None def edit_item(self): name = unicode(self._listwidget.currentItem().text()) self.parent().open(Path(self.data.path()+(name,))) def delete_item(self): item_name = unicode(self._listwidget.currentItem().text()) self._listwidget.takeItem(self._listwidget.row(self._listwidget.currentItem())) del self.data[item_name] def _createItem(self, itemname): item = QListWidgetItem(itemname) item.setFlags (Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled ) self._listwidget.addItem(item) def rename_item(self, item): self.data.rename_item(self.current_item_index, unicode(item.text())) def current_item_changed(self, item): if item: self.current_item_index = unicode(item.text()) else: self.current_item_index = None def dump(self): pass
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 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 ListEdit(QWidget): """A widget to edit a list of items (e.g. a list of directories).""" # emitted when anything changed in the listbox. changed = pyqtSignal() def __init__(self, *args, **kwargs): QWidget.__init__(self, *args, **kwargs) layout = QGridLayout(self) self.setLayout(layout) self.addButton = QPushButton(icons.get('list-add'), '') self.editButton = QPushButton(icons.get('document-edit'), '') self.removeButton = QPushButton(icons.get('list-remove'), '') self.listBox = QListWidget() layout.setContentsMargins(1, 1, 1, 1) layout.setSpacing(0) layout.addWidget(self.listBox, 0, 0, 8, 1) layout.addWidget(self.addButton, 0, 1) layout.addWidget(self.editButton, 1, 1) layout.addWidget(self.removeButton, 2, 1) @self.addButton.clicked.connect def addClicked(): item = self.createItem() if self.openEditor(item): self.addItem(item) @self.editButton.clicked.connect def editClicked(): item = self.listBox.currentItem() item and self.editItem(item) @self.removeButton.clicked.connect def removeClicked(): item = self.listBox.currentItem() if item: self.removeItem(item) @self.listBox.itemDoubleClicked.connect def itemDoubleClicked(item): item and self.editItem(item) self.listBox.model().layoutChanged.connect(self.changed) def updateSelection(): selected = bool(self.listBox.currentItem()) self.editButton.setEnabled(selected) self.removeButton.setEnabled(selected) self.changed.connect(updateSelection) self.listBox.itemSelectionChanged.connect(updateSelection) updateSelection() app.translateUI(self) def translateUI(self): self.addButton.setText(_("&Add...")) self.editButton.setText(_("&Edit...")) self.removeButton.setText(_("&Remove")) def createItem(self): return QListWidgetItem() def addItem(self, item): self.listBox.addItem(item) self.itemChanged(item) self.changed.emit() def removeItem(self, item): self.listBox.takeItem(self.listBox.row(item)) self.changed.emit() def editItem(self, item): if self.openEditor(item): self.itemChanged(item) self.changed.emit() def setCurrentItem(self, item): self.listBox.setCurrentItem(item) def setCurrentRow(self, row): self.listBox.setCurrentRow(row) def openEditor(self, item): """Opens an editor (dialog) for the item. Returns True if the dialog was accepted and the item edited. Returns False if the dialog was cancelled (the item must be left unedited). """ pass def itemChanged(self, item): """Called after an item has been added or edited. Re-implement to do something at this moment if needed, e.g. alter the text or display of other items. """ pass def setValue(self, strings): """Sets the listbox to a list of strings.""" self.listBox.clear() self.listBox.addItems(strings) self.changed.emit() def value(self): """Returns the list of paths in the listbox.""" return [self.listBox.item(i).text() for i in range(self.listBox.count())] def setItems(self, items): """Sets the listbox to a list of items.""" self.listBox.clear() for item in items: self.listBox.addItem(item) self.itemChanged(item) self.changed.emit() def items(self): """Returns the list of items in the listbox.""" return [self.listBox.item(i) for i in range(self.listBox.count())] def clear(self): """Clears the listbox.""" self.listBox.clear() self.changed.emit()
class ListBox(QWidget): def __init__(self, parent): QWidget.__init__(self, parent) while not isinstance(parent, QDialog): parent = parent.parent() self.setObjectName("ListBox" + str(len(parent.findChildren(ListBox)))) self.hLayoutBoxPanel = QHBoxLayout(self) self.hLayoutBoxPanel.setSpacing(0) self.hLayoutBoxPanel.setContentsMargins(3, 3, 3, 3) self.hLayoutBoxPanel.setObjectName(("hLayoutBoxPanel")) self.frameBoxPanel = QFrame(self) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.frameBoxPanel.sizePolicy().hasHeightForWidth()) self.frameBoxPanel.setSizePolicy(sizePolicy) self.frameBoxPanel.setFrameShape(QFrame.NoFrame) self.frameBoxPanel.setFrameShadow(QFrame.Raised) self.frameBoxPanel.setObjectName(("frameBoxPanel")) self.hLayoutframeBoxPanel = QHBoxLayout(self.frameBoxPanel) self.hLayoutframeBoxPanel.setSpacing(0) self.hLayoutframeBoxPanel.setMargin(0) self.hLayoutframeBoxPanel.setObjectName(("hLayoutframeBoxPanel")) self.captionLabel = QLabel(self.frameBoxPanel) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.captionLabel.sizePolicy().hasHeightForWidth()) self.captionLabel.setSizePolicy(sizePolicy) self.captionLabel.setMinimumSize(QSize(200, 0)) self.captionLabel.setMaximumSize(QSize(200, 16777215)) font = QFont() font.setBold(False) font.setWeight(50) self.captionLabel.setFont(font) self.captionLabel.setObjectName(("captionLabel")) self.hLayoutframeBoxPanel.addWidget(self.captionLabel) self.listBox = QListWidget(self.frameBoxPanel) self.listBox.setEnabled(True) font = QFont() font.setBold(False) font.setWeight(50) self.listBox.setFont(font) self.listBox.setObjectName(("listBox")) # self.listBox.setText("0.0") self.hLayoutframeBoxPanel.addWidget(self.listBox) self.imageButton = QToolButton(self.frameBoxPanel) self.imageButton.setText(("")) icon = QIcon() icon.addPixmap(QPixmap(("Resource/convex_hull.png")), QIcon.Normal, QIcon.Off) self.imageButton.setIcon(icon) self.imageButton.setObjectName(("imageButton")) self.imageButton.setVisible(False) self.hLayoutframeBoxPanel.addWidget(self.imageButton) self.hLayoutBoxPanel.addWidget(self.frameBoxPanel) self.listBox.currentRowChanged.connect(self.listBoxChanged) self.imageButton.clicked.connect(self.imageButtonClicked) self.captionUnits = "" self.hasObject = False self.objectList = [] self.captionLabel.setVisible(False) def get_Count(self): return self.listBox.count() Count = property(get_Count, None, None, None) def method_3(self, string_0): return self.listBox.row(self.listBox.findItems(string_0)[0]) def method_11(self, string_0): if (self.IsEmpty): return "%s%s\t" % (string_0, self.Caption) return "%s%s\t%s %s" % (string_0, self.Caption, self.Value, self.CaptionUnits) def listBoxChanged(self, index): i = index self.emit(SIGNAL("Event_0"), self) def IndexOf(self, item): if isinstance(item, str): return self.listBox.row(self.listBox.findItems(item)[0]) else: return self.listBox.row( self.listBox.findItems(item.ToString())[0]) def Contains(self, item): compStr = None if isinstance(item, str): compStr = item elif isinstance(item, float) or isinstance(item, int): compStr = str(item) else: compStr = item.ToString() for i in range(self.listBox.count()): comboItemstr = self.listBox.item(i).text() if compStr == comboItemstr: return True return False def Clear(self): self.listBox.clear() self.objectList = [] self.hasObject = False def Add(self, item): if not isinstance(item, str) and not isinstance(item, QString): self.listBox.addItem(item.ToString()) self.objectList.append(item) self.hasObject = True return self.listBox.addItem(item) self.hasObject = False return self.listBox.count() - 1 def Insert(self, index, item): if not isinstance(item, str): self.listBox.insertItem(index, item.ToString()) self.objectList.insert(index, item) self.hasObject = True return self.listBox.insertItem(index, item) self.hasObject = False def imageButtonClicked(self): self.emit(SIGNAL("Event_3"), self) def get_Caption(self): caption = self.captionLabel.text() findIndex = caption.indexOf("(") if findIndex > 0: val = caption.left(findIndex) return val return caption def set_Caption(self, captionStr): if captionStr == "": self.captionLabel.setText("") self.LabelWidth = 0 return if self.CaptionUnits != "" and self.CaptionUnits != None: self.captionLabel.setText(captionStr + "(" + str(self.CaptionUnits) + ")" + ":") else: self.captionLabel.setText(captionStr + ":") Caption = property(get_Caption, set_Caption, None, None) def get_CaptionUnits(self): return self.captionUnits def set_CaptionUnits(self, captionUnits): self.captionUnits = captionUnits CaptionUnits = property(get_CaptionUnits, set_CaptionUnits, None, None) def set_ButtonVisible(self, bool): self.imageButton.setVisible(bool) ButtonVisible = property(None, set_ButtonVisible, None, None) # def get_Value(self): # return self.listBox.currentIndex() # # def set_Value(self, value): # try: # self.listBox.setCurrentIndex(value) # except: # self.textBox.setText("") # Value = property(get_Value, set_Value, None, None) # def get_IsEmpty(self): # return self.listBox.currentText() == "" or self.listBox.currentIndex() == -1 # IsEmpty = property(get_IsEmpty, None, None, None) # def get_ReadOnly(self): # return self.listBox.isReadOnly() # # def set_ReadOnly(self, bool): # # self.listBox.setR.setReadOnly(bool) # # ReadOnly = property(get_ReadOnly, set_ReadOnly, None, None) def set_LabelWidth(self, width): self.captionLabel.setMinimumSize(QSize(width, 0)) self.captionLabel.setMaximumSize(QSize(width, 16777215)) LabelWidth = property(None, set_LabelWidth, None, None) def set_Width(self, width): self.listBox.setMinimumSize(QSize(width, 0)) self.listBox.setMaximumSize(QSize(width, 16777215)) Width = property(None, set_Width, None, None) def set_Button(self, imageName): if imageName == None or imageName == "": self.imageButton.setVisible(False) return icon = QIcon() icon.addPixmap(QPixmap(("Resource/" + imageName)), QIcon.Normal, QIcon.Off) self.imageButton.setIcon(icon) self.imageButton.setVisible(True) Button = property(None, set_Button, None, None) def get_SelectedIndex(self): try: return self.listBox.currentRow() except: return 0 def set_SelectedIndex(self, index): if self.listBox.count() == 0: return if index > self.listBox.count() - 1: self.listBox.setCurrentRow(0) else: self.listBox.setCurrentRow(index) SelectedIndex = property(get_SelectedIndex, set_SelectedIndex, None, None) # def get_Value(self): # return self.listBox.currentIndex() # def set_Value(self, valueStr): # if self.listBox.count() == 0: # return # self.listBox.setCurrentIndex(self.listBox.findText(valueStr)) # Value = property(get_Value, set_Value, None, None) def get_Items(self): if self.hasObject: return self.objectList itemList = [] if self.listBox.count() > 0: for i in range(self.listBox.count()): itemList.append(self.listBox.item(i).text()) return itemList def set_AddItems(self, strList): if len(strList) != 0 and not isinstance( strList[0], str) and not isinstance(strList[0], QString): for obj in strList: self.listBox.addItem(obj.ToString()) self.objectList.append(obj) self.hasObject = True return self.listBox.addItems(strList) Items = property(get_Items, set_AddItems, None, None) def get_Enabled(self): return self.listBox.isEnabled() def set_Enabled(self, bool): self.listBox.setEnabled(bool) Enabled = property(get_Enabled, set_Enabled, None, None) def get_Visible(self): return self.isVisible() def set_Visible(self, bool): self.setVisible(bool) Visible = property(get_Visible, set_Visible, None, None) def get_SelectedItem(self): if self.listBox.count() == 0: return None if self.hasObject: return self.objectList[self.SelectedIndex] return self.listBox.currentItem().text() # def set_SelectedItem(self, val): # index = self.listBox.findText(val) # self.listBox.setCurrentIndex(index) SelectedItem = property(get_SelectedItem, None, None, None)
class FileSelector(QDialog): def __init__(self, parent=None): super(FileSelector, self).__init__(parent, Qt.Dialog | Qt.FramelessWindowHint) self.setObjectName("file-selector") self._files = {} self.effect = QGraphicsOpacityEffect() self.setGraphicsEffect(self.effect) self.animation = QPropertyAnimation(self.effect, "opacity") self.animation.setDuration(1500) box = QVBoxLayout(self) box.setSpacing(30) self.list_of_files = QListWidget() self.list_of_files.setObjectName("list-selector") box.addWidget(self.list_of_files) self.label_path = QLabel() box.addWidget(self.label_path) self._load_files() self.connect(self.list_of_files, SIGNAL("itemSelectionChanged()"), self._update_label) self.connect(self.list_of_files, SIGNAL("itemActivated(QListWidgetItem*)"), self._open_file) self.connect(self.list_of_files, SIGNAL("itemEntered(QListWidgetItem*)"), self._open_file) def _load_files(self): """ Carga los archivos abiertos en la lista """ editor_container = Edis.get_component("principal") opened_files = editor_container.opened_files_for_selector() for _file in opened_files: base_name = os.path.basename(_file) self._files[base_name] = _file self.list_of_files.addItem(base_name) index = editor_container.current_index() self.list_of_files.setCurrentRow(index) self._update_label() def _update_label(self): """ Actualiza el QLabel """ item = self.list_of_files.currentItem() show_in_label = self._files.get(item.text()) self.label_path.setText(show_in_label) def _open_file(self, item): """ Cambia de archivo en el stacked """ editor_container = Edis.get_component("principal") index = self.list_of_files.row(item) editor_container.editor_widget.change_item(index) self.close() def showEvent(self, event): super(FileSelector, self).showEvent(event) self.animation.setStartValue(0) self.animation.setEndValue(1) self.animation.start()
class VocDialog(QDialog) : """This is the dialog which presents the interface and organise everything.""" MAGICWORD = 'CHANGEME' findDight = reCompile(r'\d+') baseURL = 'http://www.gstatic.com/dictionary/static/sounds/de/0/CHANGEME.mp3' def __init__(self, autoProxy=False, parent=None) : super(VocDialog, self).__init__(parent) self.logger = getLogger('VocVoc.VocDialog') self.info = self.logger.info self.warn = self.logger.warn self.debug = self.logger.debug if autoProxy : self.info('Starting VocDialog with autoProxy.') else : self.info('Starting VocDialog without autoProxy.') self.mediaObeject = Phonon.createPlayer(Phonon.MusicCategory, Phonon.MediaSource('')) self.setupUi() self.connect() self.initCountWord() self.candidates = None self.autoProxy = autoProxy self.spellChecker = SpellChecker() self.correct = self.spellChecker.correct self.corpusDir = self.spellChecker.corpusDir self.info('VocDialog started.') def keyPressEvent(self, event) : self.debug('Key is {}.'.format(event.key())) super(VocDialog, self).keyPressEvent(event) def resizeEvent(self, event) : self.debug("Resized to {}.".format(self.size())) super(VocDialog, self).resizeEvent(event) def initCountWord(self) : """ The first one is a count about how many time the input is wrong. WRONG : Not collected in or can be corrected by the wordModel. The second one is the last time's wrong input. """ self.countWord = [0, ''] def setupUi(self) : "Setup the UI." self.info('Seting up the UI.') self.fileDialog = QFileDialog() self.fileDialog.setFileMode(QFileDialog.AnyFile) self.fileDialog.setViewMode(QFileDialog.Detail) self.loadButton = QPushButton( r'Open/New :', self) self.loadButton.setAutoDefault(False) self.textList = QListWidget(self) self.inputLine = tabEnabledLineEdit(self) self.toggleButton = QPushButton(r'Show/Hide', self) self.toggleButton.setAutoDefault(False) self.toggleButton.setCheckable(True) self.textLabel = QLabel() self.hBox = QHBoxLayout() self.hBox.addWidget(self.inputLine) self.hBox.addWidget(self.toggleButton) self.statusBar = QStatusBar(self) msg = 'Hello World! I love YOU!!!' self.statusBar.showMessage(msg, 5000) vBox = QVBoxLayout() items = [self.loadButton, self.textList, self.hBox, self.statusBar] for item in items : try : vBox.addWidget(item) except : vBox.addLayout(item) self.textViewer = QTextEdit() self.textViewer.setHidden(True) self.textViewer.setReadOnly(True) HBox = QHBoxLayout() items = [vBox, self.textViewer] for item in items : try : HBox.addWidget(item) except : HBox.addLayout(item) self.setLayout(HBox) self.resize(350, 500) self.setWindowTitle("VocVoc -- Your Vocabulary Helper") self.info('UI is set up now.') def connect(self) : "Connect signals and slots in the UI." self.info('Connecting signals and slots.') self.loadButton.clicked.connect(self.loadFile) self.inputLine.returnPressed.connect(self.enteredText) self.inputLine.ctrlN.connect(self.completeHandler) self.inputLine.ctrlP.connect(lambda : self.completeHandler(False)) self.textList.itemActivated.connect(self.itemActivated) self.toggleButton.clicked.connect(self.toggleViewer) if self.logger.isEnabledFor(DEBUG) : self.mediaObeject.stateChanged.connect( self.errorState ) self.info('Signals and slots connected.') def errorState(self, state) : errorStates = { 0: 'Loading', 1: 'Stopped', 2: 'Playing', 3: 'Buffering', 4: 'Paused', 5: 'Error' } msg ='{} state in Phonon!'.format( errorStates[state]) self.info(self.mediaObeject.errorType()) if state == 5 : self.warn(msg) else : self.info(msg) def itemActivated(self, item) : row = self.textList.row(item) text = item.text() if not text.startswith('#') : self.pronounce(item.text()) self.findWord(text) if row+1 != self.textList.count() : self.debug('NOT last row!') self.textList.setCurrentRow(row+1) else : self.debug('Last row!') def toggleViewer(self) : if self.textViewer.isHidden() : self.resize(700, 500) self.textViewer.show() else : self.textViewer.hide() self.resize(350, 500) def backAndForward(self, forward=True) : inputLine = self.inputLine word = inputLine.text() setText = inputLine.setText candidates = self.candidates count = len(candidates) try : position = candidates.index(word) self.debug('Position found.') except : position = None self.debug('Position not found.') if forward : if position is None or position == count - 1 : # At end position = -1 setText( candidates[position+1] ) else : if position is None or position == 0 : position = count setText( candidates[position-1] ) def completeHandler(self, goNext=True) : inputLine = self.inputLine candidates = self.candidates word = inputLine.text() if candidates : self.backAndForward(goNext) def play(self, path) : self.mediaObeject.setCurrentSource(Phonon.MediaSource(path)) self.mediaObeject.play() def pronounce(self, word) : self.info('Preparing the url to pronounce.') url = self.baseURL.replace(self.MAGICWORD, word) if not self.autoProxy : self.debug('Without the autoProxy, play it using the url as the source.') self.play(url) else : self.info('With the autoProxy, play it after downloading the file.') try : # May happen HTTPError. resource = urlopen(url).read() tempFile = NamedTemporaryFile() tempFile.write(resource) self.play(tempFile.name) except HTTPError as error : self.warn(repr(error)) self.warn('Pronounciation FAILED.') self.info('Pronounciation ended.') def findWord(self, word) : self.info('Finding word in the text file.') textViewer = self.textViewer if textViewer.isHidden() : return else : pass limit = 5 contexts = list() textLines = list() corpuses = glob(''.join([self.corpusDir, '/*'])) self.debug('Found corpuses : {}.'.format(corpuses)) textViewer.clear() for corpus in corpuses : textLines.append(locateWord(corpus, word)) for textLine in textLines : text, lines = textLine[0], textLine[1] title = ''.join( ['Title : ', basename(text[-1])] ) if lines : for line in lines : wantedLines = text[line-limit: line+limit] #cleanLines = map(self.replace, wantedLines) context = ''.join(wantedLines) context = context.replace(word, ' '.join(['*', word, '*'])) context = context.replace('\n\n', self.MAGICWORD) context = context.replace('\n', ' ') context = context.replace(self.MAGICWORD, '\n\n') contexts.append(''.join([title, '\n', context, '\n\n'])) if contexts : for context in contexts : textViewer.append(context) else : textViewer.append('Sorry, {} not found.'.format(word)) self.info('Word found and showed in the textViewer.') def wordCount(self, word=None) : """ This function uses self.countWord to decide whether record and pronounce the input or not. RECORD : Add the input into the textList and write it into the file. If the word itself is correct, return True. Or if a wrong input were entered twice, return True. Otherwise with a one-time-entered wrong input, return False. """ if self.countWord[0] == 0 : # The word is correct. self.countWord[1] = '' return True elif self.countWord[0] == 1 : msg = 'Maybe the word is WRONG? Playing beep and saving the word.' self.debug(msg) self.countWord[1] = word self.play('beep.mp3') return False elif self.countWord[0] == 2 : if word != self.countWord[1] : # Different word. self.debug('DIFEFRENT WORD.') self.countWord[0] = 1 # Check again. self.countWord[1] = word # Update it. self.play('beep.mp3') return False else : self.countWord[0] = 0 self.countWord[1] = '' return True else : self.countWord[0] = 0 def checkWord(self, word) : statusBar = self.statusBar showMessage = statusBar.showMessage candidates = self.correct(word) if candidates is None : # Not collected. self.countWord[0] += 1 showMessage('Are you sure?', 3000) elif candidates[0] != word : # Can be corrected. self.countWord[0] += 1 self.candidates = candidates msg = 'Do you mean {} ?'.format(' ,'.join(candidates)) showMessage(msg, 5000) else : # Collected in the wordModel. self.findWord(word) self.countWord[0] = 0 self.debug('Word collected in the wordModel.') return True msg = 'wrongTime = {} with the word {}.'.format(self.countWord[0], word) self.logger.debug(msg) return self.wordCount(word) def addText(self, text) : self.info('Starting to add text.') textList = self.textList if text.startswith('#') : # It is a comment. pass else : # It is a word. if self.checkWord(text) : self.pronounce(text) else : # self.checkWord(text) return False return self.inputLine.clear() textList.addItem(text) self.statusBar.clearMessage() textList.setCurrentRow( textList.count() - 1 ) try : # With the try statement, it can be used as a pronunciation helper. flush(self.filePath, text) except Exception : self.debug('Using this freely without writing to a file as a pronunciation helper.') self.info('Text added.') def enteredText(self) : "Get the text from the input line and add it to the file and the list." self.info('Adding text to textList and the file.') textList = self.textList text = self.inputLine.text().strip().lower() self.debug( 'Input is {}.'.format(text) ) self.addText(text) self.info('Text added.') def loadFile(self) : "Open the file dialog to select the file and try to start." # Open the file dialog. logger = getLogger('VocVoc.VocDialog.loadFile') info = logger.info debug = logger.debug debug('Preparing to load file.') textList = self.textList if ( self.fileDialog.exec() ) : debug('Dialog executed sucessfully.') filePath = self.fileDialog.selectedFiles()[0] fileName = basename(filePath) # Create or read file. try : with open(filePath, 'r+') as textFile : debug('File exists, openning up.') writenText = textFile.read() writenText = writenText.splitlines() textList.clear() textList.addItems( writenText ) if not 'end' in writenText[-1].strip().lower() : textList.setCurrentRow( len(writenText)-1 ) else : textList.setCurrentRow( 0 ) debug('Added items to list and set current row to the last row.') except IOError as error : # File does not exist. We create one. debug('File does not exist. Trying to find the dight in the name.') listNumber = self.findDight.search(fileName) if listNumber is None : # No number found in the text. logger.warn('Dight not found in the filename. Try again.') msg = 'No number found in the file name.\nPlease try again.' QMessageBox.warning(self, 'List number NOT found.', msg, QMessageBox.Ok) return msg else : # No existing file but found the number in the file name. debug('Dight Found. Creating file and adding first line.') with open(filePath, 'x') as textFile : firstLine = ''.join( ['# list ' ,str( listNumber.group() )] ) # Cannot put '\n' here. textFile.write( ''.join([firstLine ,'\n']) ) textList.clear() textList.addItem(firstLine) # Otherwise there would be a new line in the list. debug('Set inputLine to write-enabled.') self.inputLine.setReadOnly(False) debug('Pass textFile to the dialog') self.filePath = filePath info('File loaded.')
class MainWidget( QWidget ): def __init__(self, parent = None ): super(MainWidget, self).__init__( parent ) self.people = [] self.selectedPerson = None self.requestWorker = RequestWorker( Common.FACEBOOK_INFO_SERVER_ADDRESS ) self.levelOptions = None mainLayout = QVBoxLayout( self ) title = QLabel( "Faceland" ) mainLayout.addWidget( title ) subLayout = QHBoxLayout() self.peopleView = QListWidget() self.peopleView.itemClicked.connect( self.onPersonSelected ) subLayout.addWidget( self.peopleView, 1 ) #form layout formLayout = QFormLayout() self.levelNameLabel = QLabel() self.levelDifficultyLabel = QLabel() self.numberOfEnemiesLabel = QLabel() self.playerSpeedLabel = QLabel() self.enemySpeedLabel = QLabel() self.playerDamage = QLabel() self.backgroundTexture = QLabel() self.person_name = "" self.logWithFacebookButton = QPushButton( "Log With Facebook ") self.logWithFacebookButton.clicked.connect( self.onLogButtonClicked) self.launchButton = QPushButton( "Launch" ) self.launchButton.setEnabled(False) self.launchButton.clicked.connect( self.onLaunchButtonClicked ) formLayout.addRow( self.logWithFacebookButton , self.launchButton ) formLayout.addRow( QLabel( "Level Difficulty" ), self.levelDifficultyLabel ) formLayout.addRow( QLabel( "Enemies" ), self.numberOfEnemiesLabel ) formLayout.addRow( QLabel( "Player Speed" ), self.playerSpeedLabel ) formLayout.addRow( QLabel( "Enemy Speed" ), self.enemySpeedLabel ) formLayout.addRow( QLabel( "Damage" ), self.playerDamage ) formLayout.addRow( QLabel( "World" ), self.backgroundTexture ) subLayout.addLayout( formLayout, 1 ) mainLayout.addLayout( subLayout ) # DO NOT REMOVE COPYRIGHT INFORMATION! Licensed under CC BY SA mainLayout.addWidget(QLabel("Theme song: 'Free Software Song 2' by Jono Bacon CC BY SA")) self.setLayout( mainLayout ) def resetPeoplesWidget(self, aPeople ): self.peopleView.clear() self.people = aPeople for person in aPeople: item = QListWidgetItem( str(person.name) ) # item. self.peopleView.addItem( item ) def setPeople( self, aPeople ): self.resetPeoplesWidget( aPeople ) def onPersonSelected( self, item ): row = self.peopleView.row( item ) self.selectedPerson = self.people[ row ] print ( "{0} is selected".format( self.selectedPerson.name ) ) self.levelOptions = Common.Level( self.selectedPerson.name, self.selectedPerson.data ) self.updateFormFromSelectedUser() self.launchButton.setEnabled(True) def onLaunchButtonClicked( self ): game = Game(self.levelOptions) game.run() print ( "Launch Button Clicked" ) def onLogButtonClicked(self): people = self.requestWorker.request() self.setPeople( people ) def updateFormFromSelectedUser(self): self.levelDifficultyLabel.setText( Common.Level.LevelDifficultyToString( self.levelOptions.enemiesDifficulty ) ) self.numberOfEnemiesLabel.setText( str( self.levelOptions.enemiesCount ) ) self.enemySpeedLabel.setText( str(self.levelOptions.enemySpeed)) self.playerSpeedLabel.setText( str(self.levelOptions.playerSpeed)) self.playerDamage.setText( str(self.levelOptions.damage)) pix = QPixmap( self.levelOptions.enumTexture.value ) self.backgroundTexture.setStyleSheet("border-image:url(:/2.png);") self.backgroundTexture.setPixmap( pix.scaled( 150, 150 ) )
class LayerImportBrowser(QDialog): class VectorPage(QWidget): def __init__(self, parent=None, filters="", encodings=[]): QWidget.__init__(self, parent) self.filters = filters self.layerLineEdit = QLineEdit() self.browseToolButton = QToolButton() self.browseToolButton.setAutoRaise(True) self.browseToolButton.setIcon(QIcon(":document-open")) layerLabel = QLabel("&Dataset:") layerLabel.setBuddy(self.layerLineEdit) self.encodingComboBox = QComboBox() self.encodingComboBox.addItems(encodings) encodingLabel = QLabel("&Encoding:") encodingLabel.setBuddy(self.encodingComboBox) hbox = QHBoxLayout() hbox.addWidget(layerLabel) hbox.addWidget(self.layerLineEdit) hbox.addWidget(self.browseToolButton) vbox = QVBoxLayout() vbox.addLayout(hbox) hbox = QHBoxLayout() hbox.addWidget(encodingLabel) hbox.addWidget(self.encodingComboBox) vbox.addLayout(hbox) self.setLayout(vbox) self.encodingComboBox.setCurrentIndex(self.encodingComboBox.findText("System")) self.connect(self.browseToolButton, SIGNAL("clicked()"), self.browseToFile) self.connect(self.encodingComboBox, SIGNAL("currentIndexChanged(QString)"), self.changeEncoding) def browseToFile(self): dialog = QFileDialog(self, "manageR - Open Vector File", unicode(robjects.r.getwd()[0]), self.filters) if not dialog.exec_() == QDialog.Accepted: return files = dialog.selectedFiles() file = files.first().trimmed() self.layerLineEdit.setText(file) self.emit(SIGNAL("filePathChanged(QString)"), file) def changeEncoding(self, text): self.emit(SIGNAL("encodingChanged(QString)"), text) class RasterPage(QWidget): def __init__(self, parent=None, filters=""): QWidget.__init__(self, parent) self.parent = parent self.filters = filters self.layerLineEdit = QLineEdit() self.browseToolButton = QToolButton() self.browseToolButton.setAutoRaise(True) self.browseToolButton.setIcon(QIcon(":document-open")) layerLabel = QLabel("&Dataset:") layerLabel.setBuddy(self.layerLineEdit) hbox = QHBoxLayout() hbox.addWidget(layerLabel) hbox.addWidget(self.layerLineEdit) hbox.addWidget(self.browseToolButton) vbox = QVBoxLayout() vbox.addLayout(hbox) self.setLayout(vbox) self.connect(self.browseToolButton, SIGNAL("clicked()"), self.browseToFile) def browseToFile(self): dialog = QFileDialog(self, "manageR - Open Raster File", unicode(robjects.r.getwd()[0]), self.filters) if not dialog.exec_() == QDialog.Accepted: return files = dialog.selectedFiles() file = files.first().trimmed() self.layerLineEdit.setText(file) self.emit(SIGNAL("filePathChanged(QString)"), file) def __init__(self, parent=None, vectors="", rasters="", encodings=[]): QDialog.__init__(self, parent) self.contentsWidget = QListWidget() self.setWindowIcon(QIcon(":icon")) self.contentsWidget.setViewMode(QListView.IconMode) self.contentsWidget.setIconSize(QSize(76, 66)) self.contentsWidget.setMovement(QListView.Static) self.contentsWidget.setMaximumWidth(106) self.contentsWidget.setMinimumWidth(106) self.contentsWidget.setMinimumHeight(220) self.contentsWidget.setSpacing(12) self.__filePath = "" self.__encoding = "System" self.__type = 0 self.pagesWidget = QStackedWidget() vectorPage = self.VectorPage(self, vectors, encodings) self.pagesWidget.addWidget(vectorPage) rasterPage = self.RasterPage(self, rasters) self.pagesWidget.addWidget(rasterPage) buttons = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel, Qt.Horizontal, self) self.connect(buttons, SIGNAL("accepted()"), self.accept) self.connect(buttons, SIGNAL("rejected()"), self.reject) self.connect(vectorPage, SIGNAL("filePathChanged(QString)"), self.setFilePath) self.connect(vectorPage, SIGNAL("encodingChanged(QString)"), self.setEncoding) self.connect(rasterPage, SIGNAL("filePathChanged(QString)"), self.setFilePath) self.createIcons() self.contentsWidget.setCurrentRow(0) horizontalLayout = QHBoxLayout() horizontalLayout.addWidget(self.contentsWidget) horizontalLayout.addWidget(self.pagesWidget, 1) mainLayout = QVBoxLayout() mainLayout.addLayout(horizontalLayout) mainLayout.addStretch(1) mainLayout.addSpacing(12) mainLayout.addWidget(buttons) self.setLayout(mainLayout) self.setWindowTitle("manageR - Import Layer") def createIcons(self): vectorButton = QListWidgetItem(self.contentsWidget) vectorButton.setIcon(QIcon(":custom-vector.svg")) vectorButton.setText("Vector Layer") vectorButton.setTextAlignment(Qt.AlignHCenter) vectorButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) rasterButton = QListWidgetItem(self.contentsWidget) rasterButton.setIcon(QIcon(":custom-raster.svg")) rasterButton.setText("Raster Layer") rasterButton.setTextAlignment(Qt.AlignHCenter) rasterButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.connect(self.contentsWidget, SIGNAL("currentItemChanged(QListWidgetItem*, QListWidgetItem*)"), self.changePage) def changePage(self, current, previous): if not current: current = previous self.pagesWidget.setCurrentIndex(self.contentsWidget.row(current)) def filePath(self): return self.__filePath def setFilePath(self, filePath): self.__filePath = filePath def encoding(self): return self.__encoding def setEncoding(self, encoding): self.__encoding = encoding def layerType(self): return self.__type def setLayerType(self, type): self.__type = type def accept(self): self.__type = self.pagesWidget.currentIndex() QDialog.accept(self)
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 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 ListEdit(QWidget): """A widget to edit a list of items (e.g. a list of directories).""" # emitted when anything changed in the listbox. changed = pyqtSignal() def __init__(self, *args, **kwargs): QWidget.__init__(self, *args, **kwargs) layout = QGridLayout(self) self.setLayout(layout) self.addButton = QPushButton(icons.get('list-add'), '') self.editButton = QPushButton(icons.get('document-edit'), '') self.removeButton = QPushButton(icons.get('list-remove'), '') self.listBox = QListWidget() layout.setContentsMargins(1, 1, 1, 1) layout.setSpacing(0) layout.addWidget(self.listBox, 0, 0, 4, 1) layout.addWidget(self.addButton, 0, 1) layout.addWidget(self.editButton, 1, 1) layout.addWidget(self.removeButton, 2, 1) @self.addButton.clicked.connect def addClicked(): item = self.createItem() if self.openEditor(item): self.addItem(item) @self.editButton.clicked.connect def editClicked(): item = self.listBox.currentItem() item and self.editItem(item) @self.removeButton.clicked.connect def removeClicked(): item = self.listBox.currentItem() if item: self.removeItem(item) @self.listBox.itemDoubleClicked.connect def itemDoubleClicked(item): item and self.editItem(item) self.listBox.model().layoutChanged.connect(self.changed) def updateSelection(): selected = bool(self.listBox.currentItem()) self.editButton.setEnabled(selected) self.removeButton.setEnabled(selected) self.changed.connect(updateSelection) self.listBox.itemSelectionChanged.connect(updateSelection) updateSelection() app.translateUI(self) def translateUI(self): self.addButton.setText(_("&Add...")) self.editButton.setText(_("&Edit...")) self.removeButton.setText(_("&Remove")) def createItem(self): return QListWidgetItem() def addItem(self, item): self.listBox.addItem(item) self.itemChanged(item) self.changed.emit() def removeItem(self, item): self.listBox.takeItem(self.listBox.row(item)) self.changed.emit() def editItem(self, item): if self.openEditor(item): self.itemChanged(item) self.changed.emit() def setCurrentItem(self, item): self.listBox.setCurrentItem(item) def setCurrentRow(self, row): self.listBox.setCurrentRow(row) def openEditor(self, item): """Opens an editor (dialog) for the item. Returns True if the dialog was accepted and the item edited. Returns False if the dialog was cancelled (the item must be left unedited). """ pass def itemChanged(self, item): """Called after an item has been added or edited. Re-implement to do something at this moment if needed, e.g. alter the text or display of other items. """ pass def setValue(self, strings): """Sets the listbox to a list of strings.""" self.listBox.clear() self.listBox.addItems(strings) self.changed.emit() def value(self): """Returns the list of paths in the listbox.""" return [ self.listBox.item(i).text() for i in range(self.listBox.count()) ] def setItems(self, items): """Sets the listbox to a list of items.""" self.listBox.clear() for item in items: self.listBox.addItem(item) self.itemChanged(item) self.changed.emit() def items(self): """Returns the list of items in the listbox.""" return [self.listBox.item(i) for i in range(self.listBox.count())] def clear(self): """Clears the listbox.""" self.listBox.clear() self.changed.emit()