class CompleterWidget(QCompleter): def __init__(self, editor): QCompleter.__init__(self) self.setWidget(editor) self.popupView = QListWidget() self.popupView.setAlternatingRowColors(True) self.popupView.setWordWrap(False) self.setPopup(self.popupView) self.setCompletionMode(QCompleter.PopupCompletion) self.setCaseSensitivity(Qt.CaseInsensitive) self.connect(self.popupView, SIGNAL("itemClicked(QListWidgetItem*)"), self.insert_completion) def insert_completion(self): insert = self.popupView.currentItem().text() extra = insert.length() - self.completionPrefix().length() self.widget().textCursor().insertText(insert.right(extra)) self.popup().hide() def complete(self, cr, results): self.popupView.clear() model = self.obtain_model_items(results) self.setModel(model) self.popup().setCurrentIndex(model.index(0, 0)) cr.setWidth(self.popup().sizeHintForColumn(0) \ + self.popup().verticalScrollBar().sizeHint().width() + 10) self.popupView.updateGeometries() QCompleter.complete(self, cr) def obtain_model_items(self, proposals): proposals.sort() for p in proposals: self.popupView.addItem(QListWidgetItem(p)) return self.popupView.model()
class Completer(QCompleter): def __init__(self, editor, project): QCompleter.__init__(self) self.icons = { 'function': QIcon(resources.images['function']), 'instance': QIcon(resources.images['attribute']), 'module': QIcon(resources.images['module']), 'class': QIcon(resources.images['class']) } self._editor = editor self._fromProject = False if project is not None: if type(project) is str: project = rope.base.project.Project(project, None, '.ninjaproject') self._project = project self._fromProject = True else: self._project = rope.base.project.get_no_project() self.setWidget(self._editor) self.popupView = QListWidget() self.popupView.setAlternatingRowColors(True) self.popupView.setWordWrap(False) self.setPopup(self.popupView) self.setCompletionMode(QCompleter.PopupCompletion) self.setCaseSensitivity(Qt.CaseInsensitive) self.connect(self, SIGNAL("activated(QString)"), self.insert_completion) def insert_completion(self, insert): extra = insert.length() - self.completionPrefix().length() self._editor.textCursor().insertText(insert.right(extra)) def complete(self, cr): if self._project: try: self.popupView.clear() code = str(self._editor.toPlainText()) start = self._editor.textCursor().position() if self._fromProject: self._project.validate() proposals = codeassist.code_assist(self._project, code, start) proposals = codeassist.sorted_proposals(proposals) model = self.obtain_model_items(proposals) self.setModel(model) self.popup().setCurrentIndex(model.index(0, 0)) cr.setWidth(self.popup().sizeHintForColumn(0) \ + self.popup().verticalScrollBar().sizeHint().width() + 10) self.popupView.updateGeometries() super(Completer, self).complete(cr) except: return def obtain_model_items(self, proposals): for p in proposals: if p.type == 'function': self.popupView.addItem( QListWidgetItem( self.icons[p.type], '%s(%s)' % (p.name, ', '.join([ n for n in p.pyname.get_object().get_param_names() if n != 'self' ])))) else: self.popupView.addItem( QListWidgetItem( self.icons.get(p.type, self.icons['class']), p.name)) return self.popupView.model() def get_path_from_project(self): if self._fromProject: return self._project.root.real_path else: return None
class MultipleFilesWidget(QWidget): """Widget that allows the selection of multiple files.""" def __init__(self, title, file_name_filter='', check_file_function=None): """Creates a new widget for selecting multiple files. - `title`: title of the file selection dialog that is opened when the user clicks on 'Add File'. - `file_name_filter`: filter to use for the selection of files (See the documentation of QFileDialog). - `check_file_function`: function that receives a file name and returns True if its contents are correct. If None, files are not checked. An error dialog is shown for the files that are not correct. The rest are just added. """ super(MultipleFilesWidget, self).__init__() self.title = title self.file_name_filter = file_name_filter self._check_file = check_file_function self.file_list = QListWidget() self.file_list.setSelectionMode(QAbstractItemView.ExtendedSelection) button_add = QPushButton(_('Add files')) self.button_remove = QPushButton(_('Remove selected')) self.button_remove.setEnabled(False) buttons = QWidget() buttons_layout = QVBoxLayout() buttons_layout.setAlignment(Qt.AlignTop) buttons.setLayout(buttons_layout) buttons_layout.addWidget(button_add) buttons_layout.addWidget(self.button_remove) main_layout = QHBoxLayout() self.setLayout(main_layout) main_layout.addWidget(self.file_list) main_layout.addWidget(buttons) button_add.clicked.connect(self._add_files) self.button_remove.clicked.connect(self._remove_files) self.file_list.selectionModel().selectionChanged.connect( \ self._selection_changed) def get_files(self): """Returns the list of selected file names.""" files = [] model = self.file_list.model() count = model.rowCount() for i in range(0, count): index = model.index(i, 0) files.append(unicode(model.data(index).toString())) return files def _add_files(self): file_list_q = QFileDialog.getOpenFileNames( self, self.title, '', self.file_name_filter, None, QFileDialog.DontUseNativeDialog) model = self.file_list.model() for file_name in file_list_q: valid = True if self._check_file is not None: valid, msg = self._check_file(unicode(file_name)) if valid: # Check if the file is already in the list: match = model.match(model.index(0, 0), 0, file_name, 1, Qt.MatchExactly) if len(match) == 0: self.file_list.addItem(file_name) def _remove_files(self): ranges = self.file_list.selectionModel().selection() model = self.file_list.model() to_remove = [] for r in ranges: to_remove.extend(range(r.top(), r.bottom() + 1)) for row in sorted(to_remove, reverse=True): model.removeRow(row) def _selection_changed(self, deselected, selected): if len(self.file_list.selectionModel().selection()) > 0: self.button_remove.setEnabled(True) else: self.button_remove.setEnabled(False)
class ComboCheckBox(QComboBox): def __init__(self, itemdicts): # items==[str,str...] super(ComboCheckBox, self).__init__() self.itemdict = itemdicts self.items = self.itemdict.keys() self.items.insert(0, u'全部') self.row_num = len(self.items) self.Selectedrow_num = 0 self.qCheckBox = [] self.qLineEdit = QLineEdit() self.qLineEdit.setReadOnly(True) self.qListWidget = QListWidget() self.addQCheckBox(0) self.qCheckBox[0].stateChanged.connect(self.All) for i in range(1, self.row_num): self.addQCheckBox(i) self.qCheckBox[i].stateChanged.connect(self.show) self.setModel(self.qListWidget.model()) self.setView(self.qListWidget) self.setLineEdit(self.qLineEdit) self.show() # self.qListWidget.setAlternatingRowColors(True) # self.qLineEdit.setAlternatingRowColors(True) # self.qLineEdit.setStyleSheet("background-color:transparen ") # self.qListWidget.setStyleSheet("background-color:#ee3333 ") def addQCheckBox(self, i): self.qCheckBox.append(QCheckBox()) qItem = QListWidgetItem(self.qListWidget) self.qCheckBox[i].setText(self.items[i]) if i > 0 and self.itemdict[self.items[i]] == "1": self.qCheckBox[i].setChecked(True) self.qListWidget.setItemWidget(qItem, self.qCheckBox[i]) def Selectlist(self): Outputlist = [] for i in range(1, self.row_num): if self.qCheckBox[i].isChecked() == True: Outputlist.append(self.qCheckBox[i].text()) self.Selectedrow_num = len(Outputlist) return Outputlist def show(self): show = '' Outputlist = self.Selectlist() self.qLineEdit.setReadOnly(False) self.qLineEdit.clear() for i in Outputlist: show += i + ';' if self.Selectedrow_num == 0: self.qCheckBox[0].setCheckState(0) elif self.Selectedrow_num == self.row_num - 1: self.qCheckBox[0].setCheckState(2) else: self.qCheckBox[0].setCheckState(1) self.qLineEdit.setText(show) self.qLineEdit.setReadOnly(True) def All(self, state): if state == 2: for i in range(1, self.row_num): self.qCheckBox[i].setChecked(True) elif state == 1: if self.Selectedrow_num == 0: self.qCheckBox[0].setCheckState(2) elif state == 0: self.clear() def clear(self): for i in range(self.row_num): self.qCheckBox[i].setChecked(False)
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()
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 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 Completer(QCompleter): def __init__(self, editor, project): QCompleter.__init__(self) self.icons = {'function': QIcon(resources.images['function']), 'instance': QIcon(resources.images['attribute']), 'module': QIcon(resources.images['module']), 'class': QIcon(resources.images['class'])} self._editor = editor self._fromProject = False if project is not None: if type(project) is str: project = rope.base.project.Project(project, None, '.ninjaproject') self._project = project self._fromProject = True else: self._project = rope.base.project.get_no_project() self.setWidget(self._editor) self.popupView = QListWidget() self.popupView.setAlternatingRowColors(True) self.popupView.setWordWrap(False) self.setPopup(self.popupView) self.setCompletionMode(QCompleter.PopupCompletion) self.setCaseSensitivity(Qt.CaseInsensitive) self.connect(self, SIGNAL("activated(QString)"), self.insert_completion) def insert_completion(self, insert): extra = insert.length() - self.completionPrefix().length() self._editor.textCursor().insertText(insert.right(extra)) def complete(self, cr): if self._project: try: self.popupView.clear() code = str(self._editor.toPlainText()) start = self._editor.textCursor().position() if self._fromProject: self._project.validate() proposals = codeassist.code_assist(self._project, code, start) proposals = codeassist.sorted_proposals(proposals) model = self.obtain_model_items(proposals) self.setModel(model) self.popup().setCurrentIndex(model.index(0, 0)) cr.setWidth(self.popup().sizeHintForColumn(0) \ + self.popup().verticalScrollBar().sizeHint().width() + 10) self.popupView.updateGeometries() super(Completer, self).complete(cr) except: return def obtain_model_items(self, proposals): for p in proposals: if p.type == 'function': self.popupView.addItem(QListWidgetItem(self.icons[p.type], '%s(%s)' % (p.name, ', '.join( [n for n in p.pyname.get_object().get_param_names() if n != 'self'])))) else: self.popupView.addItem(QListWidgetItem( self.icons.get(p.type, self.icons['class']), p.name)) return self.popupView.model() def get_path_from_project(self): if self._fromProject: return self._project.root.real_path else: return None