当前位置: 首页>>代码示例>>Python>>正文


Python QListView.selectedIndexes方法代码示例

本文整理汇总了Python中PyQt4.QtGui.QListView.selectedIndexes方法的典型用法代码示例。如果您正苦于以下问题:Python QListView.selectedIndexes方法的具体用法?Python QListView.selectedIndexes怎么用?Python QListView.selectedIndexes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PyQt4.QtGui.QListView的用法示例。


在下文中一共展示了QListView.selectedIndexes方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: OWEditDomain

# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import selectedIndexes [as 别名]
class OWEditDomain(widget.OWWidget):
    name = "Edit Domain"
    description = "Rename features and their values."
    icon = "icons/EditDomain.svg"
    priority = 3125

    inputs = [("Data", Orange.data.Table, "set_data")]
    outputs = [("Data", Orange.data.Table)]

    settingsHandler = settings.DomainContextHandler()

    domain_change_hints = settings.ContextSetting({})
    selected_index = settings.ContextSetting({})

    autocommit = settings.Setting(False)

    def __init__(self):
        super().__init__()

        self.data = None
        self.input_vars = ()
        self._invalidated = False

        box = gui.widgetBox(self.controlArea, "Domain Features")

        self.domain_model = itemmodels.VariableListModel()
        self.domain_view = QListView(
            selectionMode=QListView.SingleSelection
        )
        self.domain_view.setModel(self.domain_model)
        self.domain_view.selectionModel().selectionChanged.connect(
            self._on_selection_changed)
        box.layout().addWidget(self.domain_view)

        box = gui.widgetBox(self.controlArea, "Reset")
        gui.button(box, self, "Reset selected", callback=self.reset_selected)
        gui.button(box, self, "Reset all", callback=self.reset_all)

        gui.auto_commit(self.controlArea, self, "autocommit", "Commit",
                        "Commit on change is on")

        box = gui.widgetBox(self.mainArea, "Edit")
        self.editor_stack = QtGui.QStackedWidget()

        self.editor_stack.addWidget(DiscreteVariableEditor())
        self.editor_stack.addWidget(ContinuousVariableEditor())
        self.editor_stack.addWidget(VariableEditor())

        box.layout().addWidget(self.editor_stack)

    @check_sql_input
    def set_data(self, data):
        """Set input data set."""
        self.closeContext()
        self.clear()
        self.data = data

        if self.data is not None:
            self._initialize()
            self.openContext(self.data)
            self._restore()

        self.unconditional_commit()

    def clear(self):
        """Clear the widget state."""
        self.data = None
        self.domain_model[:] = []
        self.input_vars = []
        self.domain_change_hints = {}
        self.selected_index = -1

    def reset_selected(self):
        """Reset the currently selected variable to its original state."""
        ind = self.selected_var_index()
        if ind >= 0:
            var = self.input_vars[ind]
            desc = variable_description(var)
            if desc in self.domain_change_hints:
                del self.domain_change_hints[desc]

            self.domain_model[ind] = var
            self.editor_stack.currentWidget().set_data(var)
            self._invalidate()

    def reset_all(self):
        """Reset all variables to their original state."""
        self.domain_change_hints = {}
        if self.data is not None:
            # To invalidate stored hints
            self.domain_model[:] = self.input_vars
            itemmodels.select_row(self.domain_view, self.selected_index)
            self._invalidate()

    def selected_var_index(self):
        """Return the selected row in 'Domain Features' view."""
        rows = self.domain_view.selectedIndexes()
        assert len(rows) <= 1
        return rows[0].row() if rows else -1

#.........这里部分代码省略.........
开发者ID:Coding4Sec,项目名称:orange3,代码行数:103,代码来源:oweditdomain.py

示例2: _ListModel

# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import selectedIndexes [as 别名]
class AutoCompleteListBox:
    """
        This contains a QLineEdit and a QListView.
        
        The QListView is populated with the given data.
        When the text of QLineEdit changes, the QListView
        is filtered to keep only those containing a substring of
        the text. If QLineEdit is emptied, all data is returned to the
        QListView. 
    """
    
    class _ListModel(QAbstractListModel):
        """
            A list model that uses a list of tuples (x, y) where
            x is the string representation to show in the list, and 
            y is an object to store against it.
        """
        
        def __init__(self, listData, parent=None, *args):         
            QAbstractTableModel.__init__(self, parent, *args) 
            self.listData = listData
     
        def rowCount(self, parent=QModelIndex()):
            if not self.listData:
                return 0
            return len(self.listData) 
     
        def data(self, index, role): 
            if index.isValid() and role == Qt.DisplayRole:
                return QVariant(self.listData[index.row()][0])
            else: 
                return QVariant()
    
        def replaceList(self, data):
            self.listData = data
            self.reset()
    
    def __init__(self, window, listData):
        """
            Create the list box and line edit.
        """
        
        self.window = window
        self.listData = listData
    
        self.lineEdit = QLineEdit()
        self.listBox = QListView()
        
        self.listModel = self._ListModel(listData, window)
        self.listBox.setModel(self.listModel)

        self.subList = []
        
        self.window.connect(self.lineEdit, SIGNAL("textChanged(QString)"), self._OnTextChanged)
        
    def _OnTextChanged(self):
        """
            When self.lineEdit’s text has changed, use the new text to filter
            self.listData, and put the result in the list box.
        """
        
        if str(self.lineEdit.text()) == '':
            self.listModel.replaceList(self.listData)
            self.subList = self.listData
        else:
            pattern = str(self.lineEdit.text())
            self.subList = [item for item in self.listData if item[0].lower().find(pattern.lower()) >= 0]
            self.listModel.replaceList(self.subList)
                  
    def getLineEdit(self):
        """
            The QLineEdit object used to filter the list box.
        """
        
        return self.lineEdit
                
    def getListBox(self):
        """
            The QListView object
        """
        
        return self.listBox
    
    def replaceList(self, newList):
        """
            Replaces the data in the listbox with a new list.
        """
        
        self.subList = newList
        self.listData = newList
        self.listModel.replaceList(newList)
    
    def getSelectedItems(self):
        """
            Returns the objects associated with the selected list items.
        """
        
        if self.listBox.selectedIndexes():
            return [self.subList[index.row()][1] for index in self.listBox.selectedIndexes()]
        else:
#.........这里部分代码省略.........
开发者ID:lastaardvark,项目名称:Owl,代码行数:103,代码来源:autoCompleteListBox.py

示例3: SelectionSetsWidget

# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import selectedIndexes [as 别名]
class SelectionSetsWidget(QFrame):
    """
    Widget for managing multiple stored item selections
    """
    selectionModified = Signal(bool)

    def __init__(self, parent):
        QFrame.__init__(self, parent)
        self.setContentsMargins(0, 0, 0, 0)
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(1)
        self._setNameLineEdit = QLineEdit(self)
        layout.addWidget(self._setNameLineEdit)

        self._setListView = QListView(self)
        self._listModel = QStandardItemModel(self)
        self._proxyModel = QSortFilterProxyModel(self)
        self._proxyModel.setSourceModel(self._listModel)

        self._setListView.setModel(self._proxyModel)
        self._setListView.setItemDelegate(ListItemDelegate(self))

        self._setNameLineEdit.textChanged.connect(
            self._proxyModel.setFilterFixedString)

        self._completer = QCompleter(self._listModel, self)

        self._setNameLineEdit.setCompleter(self._completer)

        self._listModel.itemChanged.connect(self._onSetNameChange)
        layout.addWidget(self._setListView)
        buttonLayout = QHBoxLayout()

        self._addAction = QAction(
            "+", self, toolTip="Add a new sort key")
        self._updateAction = QAction(
            "Update", self, toolTip="Update/save current selection")
        self._removeAction = QAction(
            "\u2212", self, toolTip="Remove selected sort key.")

        self._addToolButton = QToolButton(self)
        self._updateToolButton = QToolButton(self)
        self._removeToolButton = QToolButton(self)
        self._updateToolButton.setSizePolicy(
                QSizePolicy.MinimumExpanding, QSizePolicy.Minimum)

        self._addToolButton.setDefaultAction(self._addAction)
        self._updateToolButton.setDefaultAction(self._updateAction)
        self._removeToolButton.setDefaultAction(self._removeAction)

        buttonLayout.addWidget(self._addToolButton)
        buttonLayout.addWidget(self._updateToolButton)
        buttonLayout.addWidget(self._removeToolButton)

        layout.addLayout(buttonLayout)
        self.setLayout(layout)

        self._addAction.triggered.connect(self.addCurrentSelection)
        self._updateAction.triggered.connect(self.updateSelectedSelection)
        self._removeAction.triggered.connect(self.removeSelectedSelection)

        self._setListView.selectionModel().selectionChanged.connect(
            self._onListViewSelectionChanged)
        self.selectionModel = None
        self._selections = []

    def sizeHint(self):
        size = QFrame.sizeHint(self)
        return QSize(size.width(), 200)

    def _onSelectionChanged(self, selected, deselected):
        self.setSelectionModified(True)

    def _onListViewSelectionChanged(self, selected, deselected):
        try:
            index = self._setListView.selectedIndexes()[0]
        except IndexError:
            return
        self.commitSelection(self._proxyModel.mapToSource(index).row())

    def _onSetNameChange(self, item):
        self.selections[item.row()].name = str(item.text())

    def _setButtonStates(self, val):
        self._updateToolButton.setEnabled(val)

    def setSelectionModel(self, selectionModel):
        if self.selectionModel:
            self.selectionModel.selectionChanged.disconnect(
                self._onSelectionChanged)
        self.selectionModel = selectionModel
        self.selectionModel.selectionChanged.connect(self._onSelectionChanged)

    def addCurrentSelection(self):
        item = self.addSelection(
            SelectionByKey(self.selectionModel.selection(),
                           name="New selection",
                           key=(1, 2, 3, 10)))
        index = self._proxyModel.mapFromSource(item.index())
#.........这里部分代码省略.........
开发者ID:nagyistoce,项目名称:orange-bio,代码行数:103,代码来源:OWPIPAx.py

示例4: DirectoryWidget

# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import selectedIndexes [as 别名]

#.........这里部分代码省略.........

    def customContext(self, pos):
        index = self.listView.indexAt(pos)
        index = self.proxyModel.mapToSource(index)
        if not index.isValid():
            self.rmAction.setEnabled(False)
            self.openAction.setEnabled(False)
            self.loadAction.setEnabled(False)
        elif not self.model.isDir(index):
            info = self.model.fileInfo(index)
            suffix = info.suffix()
            if suffix in ("Rd","Rdata","RData"):
                self.loadAction.setEnabled(True)
                self.openAction.setEnabled(False)
                self.loadExternal.setEnabled(False)
            elif suffix in ("txt","csv","R","r"):
                self.openAction.setEnabled(True)
                self.loadAction.setEnabled(False)
                self.loadExternal.setEnabled(True)
            else:
                self.loadAction.setEnabled(False)
                self.openAction.setEnabled(False)
                self.loadExternal.setEnabled(True)
        menu = QMenu(self)
        for action in self.actions:
            menu.addAction(action)
        menu.exec_(self.listView.mapToGlobal(pos))

    def openItem(self):
        index = self.listView.currentIndex()
        index = self.proxyModel.mapToSource(index)
        self.emit(SIGNAL("openFileRequest(QString)"),
        self.model.filePath(index))

    def loadItem(self):
        index = self.listView.currentIndex()
        index = self.proxyModel.mapToSource(index)
        self.emit(SIGNAL("loadFileRequest(QString)"),
        self.model.filePath(index))
        
    def externalItem(self):
        index = self.listView.currentIndex()
        index = self.proxyModel.mapToSource(index)
        QDesktopServices.openUrl(QUrl(self.model.filePath(index)))

    def newFolder(self):
        text, ok = QInputDialog.getText(self,
            "New Folder", "Folder name:", QLineEdit.Normal,
            "new_folder")
        if ok:
            index = self.listView.rootIndex()
            index = self.proxyModel.mapToSource(index)
            self.model.mkdir(index, text)

    def setFolder(self):
        index = self.listView.currentIndex()
        index = self.proxyModel.mapToSource(index)
        commands = "setwd('%s')" % self.model.filePath(index)
        self.emitCommands(commands)

    def rmItem(self):
        index = self.listView.currentIndex()
        if index == self.listView.rootIndex():
            return
        yes = QMessageBox.question(self, "manageR Warning",
            "Are you sure you want to delete '%s'?" % self.model.fileName(index),
            QMessageBox.Yes|QMessageBox.Cancel)
        if not yes == QMessageBox.Yes:
            return
        index = self.proxyModel.mapToSource(index)
        if self.model.isDir(index):
            result = self.model.rmdir(index)
        else:
            result = self.model.remove(index)
        if not result:
            QMessageBox.warning(self, "manageR Error",
            "Unable to delete %s!" % self.model.fileName(index))

    def upFolder(self):
        index = self.listView.rootIndex()
        index = self.proxyModel.parent(index)
        self.listView.setRootIndex(index)
        self.rootChanged()

    def cdFolder(self):
        indexes = self.listView.selectedIndexes()
        if len(indexes) < 1:
            return
        index = indexes[0]
        if self.model.isDir(self.proxyModel.mapToSource(index)):
            self.listView.setRootIndex(index)
        self.rootChanged()
        self.listView.clearSelection()

    def synchFolder(self):
        text = robjects.r.getwd()[0]
        index = self.model.index(text, 0)
        index = self.proxyModel.mapFromSource(index)
        self.listView.setRootIndex(index)
        self.rootChanged()
开发者ID:wioota,项目名称:ftools-qgis,代码行数:104,代码来源:widgets.py

示例5: Strategies

# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import selectedIndexes [as 别名]
class Strategies(QWidget):
	def __init__(self):
		QWidget.__init__(self)
		self.setMinimumSize(250, 1)
		self.setupUI()

		self.activeStrategy = None

	def setupUI(self):
		lay = QVBoxLayout()
		lay.setContentsMargins(0, 0, 0, 0)

		self.removeButton = QPushButton(QIcon(QPixmap("img/moduleRemove.png")), "")
		self.addButton = QPushButton(QIcon(QPixmap("img/moduleAdd.png")),"")
		self.reloadButton = QPushButton(QIcon(QPixmap("img/moduleReload.png")), "")

		self.model = Model(self)
		self.list = QListView()
		self.list.setModel(self.model)
		self.list.setIconSize(QSize(32, 32))

		lay.addWidget(self.list)

		hlay = QHBoxLayout()
		hlay.setContentsMargins(0, 0, 0, 0)
		hlay.addWidget(self.reloadButton)
		hlay.addStretch()
		hlay.addWidget(self.removeButton)
		hlay.addWidget(self.addButton)
		lay.addLayout(hlay)
		self.setLayout(lay)

		self.addButton.clicked.connect(self.addButtonClick)
		self.removeButton.clicked.connect(self.removeButtonClick)
		self.reloadButton.clicked.connect(self.reloadButtonClick)

		self.list.doubleClicked.connect(self.selectStrategy)
		self.modules = {}


	def load(self, path):
		if path:
			module = self._createModule(path)
			if module is not None:
				self.model.add(module)
				self.emit(SIGNAL('moduleLoaded'), module)

	# Kompiluje moduł do wykonywania i dodaje go do listy strategii
	def addButtonClick(self):
		path = str( QFileDialog.getOpenFileName(parent=self, caption=u"Wybierz plik", filter=u"Moduły Python (*.py)", directory="../") )
		if path:
			module = self._createModule(path)
			if module is not None:
				self.model.add(module)
				self.emit(SIGNAL('moduleLoaded'), module)

	# Przeladowuje podany modul
	def reloadButtonClick(self):
		try:
			index = self.list.selectedIndexes()[0];
			module = self.model.get(index)

			newModule = self._createModule(module.__path__)

			self.model.list[index.row()] = newModule

			if self.activeStrategy == module:
				#self.activeStrategy = newModule
				#self.model.dataChanged.emit(index, index)
				self.emit(SIGNAL('moduleReloaded'), newModule)
				self.selectStrategy(index)
		except IndexError:
			pass


	# Usuwa zaznaczoną strategię
	def removeButtonClick(self):
		module = self.model.get(self.list.selectedIndexes()[0])
		self.model.remove(self.list.selectedIndexes()[0])
		self.emit(SIGNAL('moduleRemoved'), module)
		if self.activeStrategy == module:
			self.activeStrategy = None
			self.emit(SIGNAL('strategyChanged'), module, None)

	# Wybiera aktywną strategię (2xklik na liście)
	def selectStrategy(self, index = None):
		if index == None:
			index = self.list.selectedIndexes()[0];
		old = self.activeStrategy
		new = self.model.get(index)

		if old != new:
			self.activeStrategy = new
		else:
			self.activeStrategy = None

		self.model.dataChanged.emit(index, index)
		self.emit(SIGNAL('strategyChanged'), old, self.activeStrategy)

	def _verifyModule(self, module):
#.........这里部分代码省略.........
开发者ID:marad,项目名称:deadline-framework,代码行数:103,代码来源:widgets.py

示例6: OWMoleculeVisualizer

# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import selectedIndexes [as 别名]

#.........这里部分代码省略.........
            self.updateFragmentsListBox()
            self.selectedFragment = ""
        else:
            self.setFragmentSmilesCombo()
            self.updateFragmentsListBox()

        self.fragmentSmilesCombo.setEnabled(data is not None)

    def handleNewSignals(self):
        self.updateitems()

    def clear(self):
        self.smiles_var_model[:] = []
        self.title_var_model[:] = []

        self.fragmentSmilesCombo.clear()
        self.grid.clear()
        self._widgets = []
        self._items = []

        if self.__loop is not None:
            self.__loop.close()
            self.__loop = None

    def cleargrid(self):
        self.grid.clear()
        self._widgets = []

    def _update_titles(self):
        if self.data is None:
            return

        title_vars = [self.title_var_model[ind.row()]
                      for ind in self.title_var_view.selectedIndexes()]

        for item, widget in zip(self._items, self._widgets):
            inst = self.data[item.index]
            text = " / ".join(map(str, (inst[var] for var in title_vars)))
            widget.label.setText(text)

    def setFragmentSmilesCombo(self):
        if self.fragment_data:
            candidates = score_smiles_variables(self.fragment_data)
        else:
            candidates = []

        self.fragmentSmilesCombo.model()[:] = [v for v, _ in candidates]

        if self.fragmentSmilesAttr > len(candidates):
            self.fragmentSmilesAttr = 0

    def updateFragmentsListBox(self):
        if pybel is None:
            return

        fragvars = self.fragmentSmilesCombo.model()
        if 0 <= self.fragmentSmilesAttr < len(fragvars):
            fvar = fragvars[self.fragmentSmilesAttr]
        else:
            fvar = None

        if fvar:
            frags = [str(e[fvar]) for e in self.fragment_data
                     if not e[fvar].is_special()]
            self.fragmentSmiles = [""] + frags
        else:
开发者ID:JakaKokosar,项目名称:orange-bio,代码行数:70,代码来源:OWMoleculeVisualizer.py


注:本文中的PyQt4.QtGui.QListView.selectedIndexes方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。