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


Python QFileSystemModel.index方法代码示例

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


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

示例1: Explorer

# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import index [as 别名]
class Explorer(QTreeView):

    def __init__(self, parent=None):
        QTreeView.__init__(self)
        self.header().setHidden(True)
        self.setAnimated(True)

        # Modelo
        self.model = QFileSystemModel(self)
        path = QDir.toNativeSeparators(QDir.homePath())
        self.model.setRootPath(path)
        self.setModel(self.model)
        self.model.setNameFilters(["*.c", "*.h", "*.s"])
        self.setRootIndex(QModelIndex(self.model.index(path)))
        self.model.setNameFilterDisables(False)

        # Se ocultan algunas columnas
        self.hideColumn(1)
        self.hideColumn(2)
        self.hideColumn(3)

        # Conexion
        self.doubleClicked.connect(self._open_file)

        Edis.load_lateral("explorer", self)

    def _open_file(self, i):
        if not self.model.isDir(i):
            indice = self.model.index(i.row(), 0, i.parent())
            archivo = self.model.filePath(indice)
            principal = Edis.get_component("principal")
            principal.open_file(archivo)
开发者ID:centaurialpha,项目名称:edis,代码行数:34,代码来源:explorer.py

示例2: Explorador

# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import index [as 别名]
class Explorador(custom_dock.CustomDock):

    def __init__(self, parent=None):
        custom_dock.CustomDock.__init__(self)
        self.explorador = QTreeView()
        self.setWidget(self.explorador)
        self.explorador.header().setHidden(True)
        self.explorador.setAnimated(True)

        # Modelo
        self.modelo = QFileSystemModel(self.explorador)
        path = QDir.toNativeSeparators(QDir.homePath())
        self.modelo.setRootPath(path)
        self.explorador.setModel(self.modelo)
        self.modelo.setNameFilters(["*.c", "*.h", "*.s"])
        self.explorador.setRootIndex(QModelIndex(self.modelo.index(path)))
        self.modelo.setNameFilterDisables(False)

        # Se ocultan algunas columnas
        self.explorador.hideColumn(1)
        self.explorador.hideColumn(2)
        self.explorador.hideColumn(3)

        # Conexion
        self.explorador.doubleClicked.connect(self._abrir_archivo)

        EDIS.cargar_lateral("explorador", self)

    def _abrir_archivo(self, i):
        if not self.modelo.isDir(i):
            indice = self.modelo.index(i.row(), 0, i.parent())
            archivo = self.modelo.filePath(indice)
            principal = EDIS.componente("principal")
            principal.abrir_archivo(archivo)
开发者ID:ekimdev,项目名称:edis,代码行数:36,代码来源:explorador.py

示例3: load_tree

# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import index [as 别名]
    def load_tree(self, project):
        """Load the tree view on the right based on the project selected."""
        qfsm = QFileSystemModel()
        qfsm.setRootPath(project.path)
        load_index = qfsm.index(qfsm.rootPath())
        qfsm.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)
        qfsm.setNameFilterDisables(False)
        pext = ["*{0}".format(x) for x in project.extensions]
        qfsm.setNameFilters(pext)

        self._tree.setModel(qfsm)
        self._tree.setRootIndex(load_index)

        t_header = self._tree.header()
        t_header.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)
        t_header.setResizeMode(0, QHeaderView.Stretch)
        t_header.setStretchLastSection(False)
        t_header.setClickable(True)

        self._tree.hideColumn(1)  # Size
        self._tree.hideColumn(2)  # Type
        self._tree.hideColumn(3)  # Modification date
开发者ID:AnyBucket,项目名称:ninja-ide,代码行数:24,代码来源:add_to_project.py

示例4: AbstractPathCompleter

# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import index [as 别名]
class AbstractPathCompleter(AbstractCompleter):
    """Base class for PathCompleter and GlobCompleter
    """
    
    # global object. Reused by all completers
    _fsModel = QFileSystemModel()

    _ERROR = 'error'
    _HEADER = 'currentDir'
    _STATUS = 'status'
    _DIRECTORY = 'directory'
    _FILE = 'file'
    
    def __init__(self, text):
        self._originalText = text
        self._dirs = []
        self._files = []
        self._error = None
        self._status = None
        
        """hlamer: my first approach is making self._model static member of class. But, sometimes it 
        returns incorrect icons. I really can't understand when and why.
        When it is private member of instance, it seems it works
        """
        self._model = None # can't construct in the construtor, must be constructed in GUI thread
    
    @staticmethod
    def _filterHidden(paths):
        """Remove hidden and ignored files from the list
        """
        return [path for path in paths \
                    if not os.path.basename(path).startswith('.') and \
                        not core.fileFilter().regExp().match(path)]

    def _classifyRowIndex(self, row):
        """Get list item type and index by it's row
        """

        if self._error:
            assert row == 0
            return (self._ERROR, 0)
        
        if row == 0:
            return (self._HEADER, 0)
        
        row -= 1
        if self._status:
            if row == 0:
                return (self._STATUS, 0)
            row -= 1
        
        if row in range(len(self._dirs)):
            return (self._DIRECTORY, row)
        row -= len(self._dirs)
        
        if row in range(len(self._files)):
            return (self._FILE, row)
        
        assert False

    def _formatHeader(self, text):
        """Format current directory for show it in the list of completions
        """
        return '<font style="background-color: %s; color: %s">%s</font>' % \
                (QApplication.instance().palette().color(QPalette.Window).name(),
                 QApplication.instance().palette().color(QPalette.WindowText).name(),
                 htmlEscape(text))

    def rowCount(self):
        """Row count in the list of completions
        """
        if self._error:
            return 1
        else:
            count = 1  # current directory
            if self._status:
                count += 1
            count += len(self._dirs)
            count += len(self._files)
            return count

    def _iconForPath(self, path):
        """Get icon for file or directory path. Uses QFileSystemModel
        """
        if self._model is None:
            self._model = QFileSystemModel()
        
        index = self._model.index(path)
        return self._model.data(index, Qt.DecorationRole)

    def text(self, row, column):
        """Item text in the list of completions
        """
        rowType, index = self._classifyRowIndex(row)
        if rowType == self._ERROR:
            return '<font color=red>%s</font>' % htmlEscape(self._error)
        elif rowType == self._HEADER:
            return self._formatHeader(self._headerText())
        elif rowType == self._STATUS:
            return '<i>%s</i>' % htmlEscape(self._status)
#.........这里部分代码省略.........
开发者ID:daffodil,项目名称:enki,代码行数:103,代码来源:pathcompleter.py

示例5: DirectoryWidget

# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import index [as 别名]
class DirectoryWidget(RWidget):

    def __init__(self, parent, base="."):
        RWidget.__init__(self, parent)
        self.base = base
        self.model = QFileSystemModel()
        self.model.setRootPath(QDir.rootPath())
        self.proxyModel = FileSystemProxyModel()
        self.proxyModel.setDynamicSortFilter(True)
        self.proxyModel.setFilterKeyColumn(0)
        self.proxyModel.setSourceModel(self.model)
        
        self.listView = QListView(self)
        self.listView.setModel(self.proxyModel)
        index = self.model.index(QDir.currentPath())
        self.listView.setRootIndex(self.proxyModel.mapFromSource(index))
        self.listView.setContextMenuPolicy(Qt.CustomContextMenu)
        self.lineEdit = QLineEdit(self)
        
        filterLineEdit = QLineEdit()
        filterLabel = QLabel("Filter:")
        self.connect(filterLineEdit, SIGNAL("textChanged(QString)"), 
            self.proxyModel.setFilterWildcard)
        self.actions = []

        self.upAction = QAction("&Up", self)
        self.upAction.setStatusTip("Move to parent directory")
        self.upAction.setToolTip("Move to parent directory")
        self.upAction.setIcon(QIcon(":go-up"))
        self.upAction.setEnabled(True)
        self.actions.append(self.upAction)
        self.newAction = QAction("&New Directory", self)
        self.newAction.setStatusTip("Create new directory")
        self.newAction.setToolTip("Create new directory")
        self.newAction.setIcon(QIcon(":folder-new"))
        self.newAction.setEnabled(True)
        self.actions.append(self.newAction)
        self.synchAction = QAction("&Synch", self)
        self.synchAction.setStatusTip("Synch with current working directory")
        self.synchAction.setToolTip("Synch with current working directory")
        self.synchAction.setIcon(QIcon(":view-refresh"))
        self.synchAction.setEnabled(True)
        self.actions.append(self.synchAction)
        self.rmAction = QAction("&Delete", self)
        self.rmAction.setStatusTip("Delete selected item")
        self.rmAction.setToolTip("delete selected item")
        self.rmAction.setIcon(QIcon(":edit-delete"))
        self.rmAction.setEnabled(True)
        self.actions.append(self.rmAction)
        self.openAction = QAction("&Open", self)
        self.openAction.setStatusTip("Open selected R script")
        self.openAction.setToolTip("Open selected R script")
        self.openAction.setIcon(QIcon(":document-open"))
        self.openAction.setEnabled(True)
        self.actions.append(self.openAction)
        self.loadAction = QAction("&Load", self)
        self.loadAction.setStatusTip("Load selected R data")
        self.loadAction.setToolTip("Load selected R data")
        self.loadAction.setIcon(QIcon(":document-open"))
        self.loadAction.setEnabled(True)
        self.actions.append(self.loadAction)
        self.setAction = QAction("Set as &current", self)
        self.setAction.setStatusTip("Set folder as R working directory")
        self.setAction.setToolTip("Set folder as R working directory")
        self.setAction.setIcon(QIcon(":folder-home"))
        self.setAction.setEnabled(True)
        self.actions.append(self.setAction)
        self.loadExternal = QAction("Open &Externally", self)
        self.loadExternal.setStatusTip("Load file in external application")
        self.loadExternal.setToolTip("Load file in external application")
        self.loadExternal.setIcon(QIcon(":folder-system"))
        self.loadExternal.setEnabled(True)
        self.actions.append(self.loadExternal)
        self.rootChanged()
        
        hiddenAction = QAction("Toggle hidden files", self)
        hiddenAction.setStatusTip("Show/hide hidden files and folders")
        hiddenAction.setToolTip("Show/hide hidden files and folders")
        hiddenAction.setIcon(QIcon(":stock_keyring"))
        hiddenAction.setCheckable(True)

        self.connect(self.newAction, SIGNAL("triggered()"), self.newFolder)
        self.connect(self.upAction, SIGNAL("triggered()"), self.upFolder)
        self.connect(self.synchAction, SIGNAL("triggered()"), self.synchFolder)
        self.connect(self.rmAction, SIGNAL("triggered()"), self.rmItem)
        self.connect(self.openAction, SIGNAL("triggered()"), self.openItem)
        self.connect(self.loadAction, SIGNAL("triggered()"), self.loadItem)
        self.connect(self.loadExternal, SIGNAL("triggered()"), self.externalItem)
        self.connect(self.setAction, SIGNAL("triggered()"), self.setFolder)
        self.connect(hiddenAction, SIGNAL("toggled(bool)"), self.toggleHidden)
        self.connect(self.listView, SIGNAL("activated(QModelIndex)"), self.cdFolder)
        self.connect(self.listView, SIGNAL("customContextMenuRequested(QPoint)"), self.customContext)
        self.connect(self.lineEdit, SIGNAL("returnPressed()"), self.gotoFolder)

        upButton = QToolButton()
        upButton.setDefaultAction(self.upAction)
        upButton.setAutoRaise(True)
        newButton = QToolButton()
        newButton.setDefaultAction(self.newAction)
        newButton.setAutoRaise(True)
#.........这里部分代码省略.........
开发者ID:wioota,项目名称:ftools-qgis,代码行数:103,代码来源:widgets.py

示例6: in

# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import index [as 别名]
    views = []

    # for ViewType in (QColumnView, QTreeView):
    # for ViewType in (QTreeView):

    # Create the view in the splitter.
    view = TreeView(splitter)
    view.setSelectionMode(QAbstractItemView.ExtendedSelection)

    # Set the model of the view.
    view.setModel(model)
    view.hideColumn(1)
    view.hideColumn(2)
    view.hideColumn(3)
    view.setColumnWidth(30, 1)
    view.setRootIndex(model.index(QDir.currentPath(), 0))

    # Set the root index of the view as the user's home directory.
    #    view.setRoot   Index(model.index(QDir.homePath()))
    view.setAnimated(True)
    #    view.doubleClicked().connect(buttonClicked)

    colors = ["r", "g", "b", "y", "w"]

    pgwin = pg.PlotWidget(splitter)
    p1 = pgwin.getPlotItem()
    p1.showGrid(True, True)
    p1.setLogMode(False, True)
    p1.addLegend(offset=(400, 30))

    # pgwin.setConfigOptions(antialias=True)
开发者ID:bonben,项目名称:Plotter4FECs,代码行数:33,代码来源:r_viewer.py

示例7: DirView

# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import index [as 别名]
class DirView(QTreeView):
    """Base file/directory tree view"""

    def __init__(self, parent=None):
        super(DirView, self).__init__(parent)
        self.name_filters = None
        self.parent_widget = parent
        self.valid_types = None
        self.show_all = None
        self.menu = None
        self.common_actions = None
        self.__expanded_state = None
        self._to_be_loaded = None
        self.fsmodel = None
        self.setup_fs_model()
        self._scrollbar_positions = None

    # ---- Model
    def setup_fs_model(self):
        """Setup filesystem model"""
        filters = QDir.AllDirs | QDir.Files | QDir.Drives | QDir.NoDotAndDotDot
        self.fsmodel = QFileSystemModel(self)
        self.fsmodel.setFilter(filters)
        self.fsmodel.setNameFilterDisables(False)

    def install_model(self):
        """Install filesystem model"""
        self.setModel(self.fsmodel)

    def setup_view(self):
        """Setup view"""
        self.install_model()
        self.connect(self.fsmodel, SIGNAL("directoryLoaded(QString)"), lambda: self.resizeColumnToContents(0))
        self.setAnimated(False)
        self.setSortingEnabled(True)
        self.sortByColumn(0, Qt.AscendingOrder)

    def set_name_filters(self, name_filters):
        """Set name filters"""
        self.name_filters = name_filters
        self.fsmodel.setNameFilters(name_filters)

    def set_show_all(self, state):
        """Toggle 'show all files' state"""
        if state:
            self.fsmodel.setNameFilters([])
        else:
            self.fsmodel.setNameFilters(self.name_filters)

    def get_filename(self, index):
        """Return filename associated with *index*"""
        if index:
            return osp.normpath(unicode(self.fsmodel.filePath(index)))

    def get_index(self, filename):
        """Return index associated with filename"""
        return self.fsmodel.index(filename)

    def get_selected_filenames(self):
        """Return selected filenames"""
        if self.selectionMode() == self.ExtendedSelection:
            return [self.get_filename(idx) for idx in self.selectedIndexes()]
        else:
            return [self.get_filename(self.currentIndex())]

    def get_dirname(self, index):
        """Return dirname associated with *index*"""
        fname = self.get_filename(index)
        if fname:
            if osp.isdir(fname):
                return fname
            else:
                return osp.dirname(fname)

    # ---- Tree view widget
    def setup(self, name_filters=["*.py", "*.pyw"], valid_types=(".py", ".pyw"), show_all=False):
        """Setup tree widget"""
        self.setup_view()

        self.set_name_filters(name_filters)
        self.valid_types = valid_types
        self.show_all = show_all

        # Setup context menu
        self.menu = QMenu(self)
        self.common_actions = self.setup_common_actions()

    # ---- Context menu
    def setup_common_actions(self):
        """Setup context menu common actions"""
        # Filters
        filters_action = create_action(
            self, _("Edit filename filters..."), None, get_icon("filter.png"), triggered=self.edit_filter
        )
        # Show all files
        all_action = create_action(self, _("Show all files"), toggled=self.toggle_all)
        all_action.setChecked(self.show_all)
        self.toggle_all(self.show_all)

        return [filters_action, all_action]
#.........这里部分代码省略.........
开发者ID:koll00,项目名称:Gui_SM,代码行数:103,代码来源:explorer.py

示例8: SourceFileTreeWidget

# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import index [as 别名]
class SourceFileTreeWidget(QWidget):
    """ Config window"""
    def __init__(self, parent):
        super(SourceFileTreeWidget, self).__init__(parent)
        self.ui = Ui_SourceFileTreeWidget()
        self.ui.setupUi(self)
        self.file_model = QFileSystemModel()
        #self.file_model.setFilter(QDir.AllEntries | QDir.NoDot)
        self.set_filter()
        self.ui.tree.setModel(self.file_model)
        self.ui.tree.resizeColumnToContents(0)
        self.ui.custom_root.setText(QDir.currentPath())
        self.set_root()

        header = self.ui.tree.header()
        header.setResizeMode(QHeaderView.ResizeToContents)
        #header.setStretchLastSection(True)
        #header.setSortIndicator(0, Qt.AscendingOrder)
        #header.setSortIndicatorShown(True)
        #header.setClickable(True)
        self.connect(self.ui.tree, QtCore.SIGNAL('doubleClicked(QModelIndex)'), self.open_file)
        self.connect(self.ui.ok_filter, QtCore.SIGNAL('clicked()'), self.set_filter)
        self.connect(self.ui.custom_filter, QtCore.SIGNAL('returnPressed()'), self.set_filter)
        self.connect(self.ui.ok_root, QtCore.SIGNAL('clicked()'), self.set_root)
        self.connect(self.ui.custom_root, QtCore.SIGNAL('returnPressed()'), self.set_root)
        self.open_file_signal = None

    def set_open_file_signal(self, signal):
        """ callback to signal file opening """
        self.open_file_signal = signal

    def set_root(self, root=None, use_common_prefix=True):
        """ set the root path of the widget """
        curr = str(self.ui.custom_root.text())
        if not root:
            use_common_prefix = False # input text box will override it.
            root = self.ui.custom_root.text()
        else:
            self.ui.custom_root.setText(root)
        idx = self.file_model.index(root)
        self.ui.tree.setExpanded(idx, True)
        if use_common_prefix and curr == os.path.commonprefix([root, curr]):
            return

        idx = self.file_model.setRootPath(root)
        if not idx.isValid():
            logging.warn('Invalid path')
            return
        self.ui.tree.setRootIndex(idx)
        self.ui.tree.setExpanded(idx, True)

    def set_filter(self):
        """ set filter by extension """
        filters = str(self.ui.custom_filter.text()).split(';')
        self.file_model.setNameFilters(filters)
        self.file_model.setNameFilterDisables(False)

    def open_file(self, idx):
        """ emit file opening signal """
        if self.file_model.isDir(idx):
            return
        fullpath = self.file_model.filePath(idx)
        if self.open_file_signal:
            self.open_file_signal.emit(str(fullpath), 0)

    def set_file_selected(self, tab_idx):
        """ slot to associate the file in active tab """
        filename = self.sender().tabToolTip(tab_idx)
        idx = self.file_model.index(filename)
        if idx.isValid():
            self.ui.tree.selectionModel().select(idx, QItemSelectionModel.ClearAndSelect)
开发者ID:c0deforfun,项目名称:LLL,代码行数:73,代码来源:SourceFileTreeWidget.py

示例9: import

# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import index [as 别名]
http://doc.qt.nokia.com/latest/model-view-programming.html.
"""
import sys

from PyQt4.QtGui import (QApplication, QColumnView, QFileSystemModel,
                         QSplitter, QTreeView)
from PyQt4.QtCore import QDir, Qt

if __name__ == '__main__':
    app = QApplication(sys.argv)
    # Splitter to show 2 views in same widget easily.
    splitter = QSplitter()
    # The model.
    model = QFileSystemModel()
    # You can setRootPath to any path.
    model.setRootPath(QDir.rootPath())
    # List of views.
    views = []
    for ViewType in (QColumnView, QTreeView):
        # Create the view in the splitter.
        view = ViewType(splitter)
        # Set the model of the view.
        view.setModel(model)
        # Set the root index of the view as the user's home directory.
        view.setRootIndex(model.index(QDir.homePath()))
    # Show the splitter.
    splitter.show()
    # Maximize the splitter.
    splitter.setWindowState(Qt.WindowMaximized)
    # Start the main loop.
    sys.exit(app.exec_())
开发者ID:bartoleo,项目名称:PyQtExperiments,代码行数:33,代码来源:file-system.py

示例10: __init__

# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import index [as 别名]
    def __init__(self, parent=None, viewtype=None):
        """
        viewtype option specifies the file browser type of view ('tree' and 'table' are accepted, 'tree' is the default)
        :type viewtype: str
        """
        super(MainWindow, self).__init__(parent)
        #
        # MODEL (is the default PyQt QFileSystemModel)
        #
        model = QFileSystemModel()
        model.setRootPath(QDir.currentPath())  # needed to fetch files
        model.setReadOnly(False)

        #
        # VIEW
        #
        # Select the view QWidget based on command prompt parameter
        # (table and tree view supported as far as now)
        if viewtype == 'table':
            view = TableView(self)
        elif viewtype == 'tree':
            view = TreeView(self)
        else:
            raise ValueError(u"'{}' view is not recognized. 'tree' or 'table' expected.".format(viewtype))
        # passed self to use MainWindow's methods (see signal's TODO)
        logging.info(u'{}View'.format(viewtype.capitalize()))

        view.setModel(model)
        # If you set the root of the tree to the current path
        # you start much more quickly than leaving the default, that cause 
        # detection of all drives on Windows (slow)
        if last_visited_directory:
            startpath = last_visited_directory
        else:
            startpath = QDir.currentPath()
        self.curpath = startpath
        view.setRootIndex(model.index(startpath))

        # A generic 'view' attribute name is used. Don't care about the view
        # is a TreeView or a TableView or...
        self.view = view

        self.setCentralWidget(self.view)

        # STATUS BAR
        status = self.statusBar()
        status.setSizeGripEnabled(False)
        status.showMessage(tr('SB', "Ready"), 2000)
        self.status_bar = status
        # TODO: add message to the log

        wintitle = u'{} {}'.format(__title__, __date__.replace(u'-', u'.'))
        self.setWindowTitle(wintitle)

        # Selection behavior: SelectRows 
        # (important if the view is a QTableView)
        self.view.setSelectionBehavior(view.SelectRows)
        # Set extended selection mode (ExtendedSelection is a standard)
        self.view.setSelectionMode(QTreeView.ExtendedSelection)
        # Enable the context menu
        self.view.setContextMenuPolicy(Qt.CustomContextMenu)
        self.connect(self.view, 
                     SIGNAL('customContextMenuRequested(const QPoint&)'), 
                     self.on_context_menu)

        # Double click on the view
        self.view.doubleClicked.connect(self.doubleclick)

        # Selection changed
        self.connect(self.view, SIGNAL('sel_changed(PyQt_PyObject)'), 
                     self.selChanged)

        # Creating window to show the textual content of files
        self.text_window = QTextEdit()
        # hidden for now (no method show() called)

        self.addOns = []
        # let's populate self.addOns list with dynamically created AddOn instances of scripts
        for script in py_addons:
            modulename = path.splitext(path.split(script)[-1])[0]
            exec 'from scripts import {}'.format(modulename)
            try:
                exec 'self.addOns.append({}.AddOn(self))'.format(modulename)
            except BaseException as err:
                message = u'Error on script {}: {}'.format(err, modulename)
                print(message, args)
                self.status_bar.showMessage(message)
                logging.error(message)
            else:
                print(u"Loaded add-on '{}'".format(modulename))
开发者ID:iacopy,项目名称:dyr,代码行数:92,代码来源:dyr.py

示例11: mainInitial

# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import index [as 别名]
class mainInitial(QtGui.QMainWindow):
  def  __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow() #treeview  UI
        self.ui.setupUi(self)
        self.showMaximized()
        self.home=os.getcwd()
        self.fileSystemModel = QFileSystemModel()


        #self.home=self.home + "/connections"
        #print (self.home)
        self.fillGrid2(self.home)
        #self.ui.treeWidget.isSortingEnabled()
        #self.ui.treeWidget.setSortingEnabled(True)
        self.ui.treeView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.connect(self.ui.treeView, QtCore.SIGNAL("customContextMenuRequested(const QPoint &)"), self.onclick)
        #self.connect(self.ui.treeView.selectionModel(),
        #    SIGNAL("customContextMenuRequested(pressed)"), self.onclick)


#  def eventFilter(self, obj, event):
#        if event.type() in (QtCore.QEvent.MouseButtonPress, QtCore.QEvent.MouseButtonDblClick):
#            if event.button() == QtCore.Qt.LeftButton:
#                print "left"
#                return True
#            elif event.button() == QtCore.Qt.RightButton:
#                print "Right"
#                return True
#        return super(mainInitial, self).eventFilter(obj, event)
#
#       #self.button2.clicked.connect(self.on_button_clicked)
#
#       #self.button1.installEventFilter(self)

  @QtCore.pyqtSlot(QtCore.QModelIndex)
  def onclick(self,selected):
      index=self.ui.treeView.indexAt(selected)
      #getSelected= self.ui.treeView.selectedItems()
      print (index)
      fileinfo = QtCore.QFileInfo(self.fileSystemModel.fileInfo(index) )
      print (fileinfo)
      path = self.fileSystemModel.filePath(index)
      #pathABS =self.fileSystemModel.rootPath(index)
      print path
      #print pathABS
      if self.fileSystemModel.isDir(index):
          print ("es directorio")
      else:
          print ("es archivo")

      menu=QtGui.QMenu(self)
      action_1=menu.addAction("crear coneccion")
      action_1.triggered.connect(self.action1)
      action_2=menu.addAction("borrar coneccion")
      action_3=menu.addAction("Modificar coneccion")
      action_4=menu.addAction("Crear Carpeta")
      menu.exec_(QtGui.QCursor.pos())
      #menu1=self.menu.addAction(u'algo')

      #menu1.triggered.connect(self.M1clear)
      #print ("determinar si esta vacio, es archivo o carpeta derecho")

  def action1(self, index):
      print "accion lanzada action_1"
      #self.fileSystemModel.mkdir()
      #print (self.ui.treeView.indexAt(index))

  def fillGrid2(self,home):
        print (QDir.currentPath())
        self.fileSystemModel.setRootPath(QDir.currentPath())
        self.ui.treeView.setModel(self.fileSystemModel)
        self.ui.treeView.setRootIndex(self.fileSystemModel.index(QDir.currentPath()))
        self.ui.treeView.hideColumn(1)
        self.ui.treeView.hideColumn(2)
        self.ui.treeView.hideColumn(3)
开发者ID:yeimiJuarez,项目名称:SSHingON,代码行数:78,代码来源:SSHingON.py


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