本文整理汇总了Python中PyQt4.QtGui.QFileSystemModel.setRootPath方法的典型用法代码示例。如果您正苦于以下问题:Python QFileSystemModel.setRootPath方法的具体用法?Python QFileSystemModel.setRootPath怎么用?Python QFileSystemModel.setRootPath使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt4.QtGui.QFileSystemModel
的用法示例。
在下文中一共展示了QFileSystemModel.setRootPath方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: AttachmentView
# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import setRootPath [as 别名]
class AttachmentView(QListView):
""" A dockWidget displaying attachments of the current note.
"""
def __init__(self, parent=None):
super(AttachmentView, self).__init__(parent)
self.parent = parent
self.settings = parent.settings
self.model = QFileSystemModel()
self.model.setFilter(QDir.Files)
self.model.setRootPath(self.settings.attachmentPath)
self.setModel(self.model)
# self.setRootIndex(self.model.index(self.settings.attachmentPath))
self.setViewMode(QListView.IconMode)
self.setUniformItemSizes(True)
self.setResizeMode(QListView.Adjust)
self.setItemDelegate(AttachmentItemDelegate(self))
self.clicked.connect(self.click)
def contextMenuEvent(self, event):
menu = QMenu()
indice = self.selectedIndexes()
if len(indice):
menu.addAction("Insert into note", self.insert)
menu.addAction("Delete", self.delete)
else:
pass
menu.exec_(event.globalPos())
def mousePressEvent(self, event):
""" Trigger click() when an item is pressed.
"""
self.clearSelection()
QListView.mousePressEvent(self, event)
def mouseReleaseEvent(self, event):
""" Trigger click() when an item is pressed.
"""
self.clearSelection()
QListView.mouseReleaseEvent(self, event)
def insert(self):
indice = self.selectedIndexes()
for i in indice:
filePath = self.model.filePath(i)
filePath = filePath.replace(self.settings.notebookPath, "..")
fileName = os.path.basename(filePath)
text = "![%s](%s)" % (fileName, filePath)
self.parent.notesEdit.insertPlainText(text)
def delete(self):
indice = self.selectedIndexes()
for i in indice:
filePath = self.model.filePath(i)
QFile(filePath).remove()
def click(self, index):
self.setCurrentIndex(index)
示例2: Explorer
# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import setRootPath [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)
示例3: Explorador
# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import setRootPath [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)
示例4: DockFileSystem
# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import setRootPath [as 别名]
class DockFileSystem(QDockWidget):
left = Qt.LeftDockWidgetArea
right = Qt.RightDockWidgetArea
def __init__(self, parent = None):
QDockWidget.__init__(self, "File System Tree View", parent)
self.setObjectName("FileNavigatorDock")
self.fsm = QFileSystemModel(self)
tv = QTreeView(self)
tv.showColumn(1)
self.fsm.setRootPath(self.parent().workdir)
tv.setModel(self.fsm)
self.setAllowedAreas( self.left | self.right )
self.setGeometry(0,0,400,1000)
pb = QPushButton("...",self)
pb.clicked.connect(self.changeWorkdir)
self.le = QLineEdit(self)
self.le.setText(self.parent().workdir)
dockbox = QWidget(self)
hl = QHBoxLayout(dockbox)
hl.addWidget(self.le)
hl.addWidget(pb)
hll=QWidget(self)
hll.setLayout(hl)
vl = QVBoxLayout(dockbox)
dockbox.setLayout(vl)
vl.addWidget(hll)
vl.addWidget(tv)
self.setWidget(dockbox)
self.adjustSize()
self.parent().say("Vista del sistema de ficheros creada")
@pyqtSlot()
def changeWorkdir(self):
dialog=QFileDialog(self,"Elige directorio de trabajo",self.parent().workdir)
dialog.setFileMode(QFileDialog.Directory)
dialog.setAcceptMode(QFileDialog.AcceptOpen)
if dialog.exec_():
fichero = dialog.selectedFiles().first().toLocal8Bit().data()
self.parent().workdir = fichero
self.le.setText(fichero)
self.fsm.setRootPath(self.parent().workdir)
示例5: FSLineEdit
# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import setRootPath [as 别名]
class FSLineEdit(QLineEdit):
"""
A line edit with auto completion for file system folders.
"""
def __init__(self, parent=None):
QLineEdit.__init__(self, parent)
self.fsmodel = QFileSystemModel()
self.fsmodel.setRootPath("")
self.completer = QCompleter()
self.completer.setModel(self.fsmodel)
self.setCompleter(self.completer)
self.fsmodel.setFilter(QDir.Drives | QDir.AllDirs | QDir.Hidden |
QDir.NoDotAndDotDot)
def setPath(self, path):
self.setText(path)
self.fsmodel.setRootPath(path)
示例6: open_project
# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import setRootPath [as 别名]
def open_project(self, project):
project_path = project.path
qfsm = None # Should end up having a QFileSystemModel
if project_path not in self.__projects:
qfsm = QFileSystemModel()
project.model = qfsm
qfsm.setRootPath(project_path)
qfsm.setFilter(QDir.AllDirs | QDir.Files | QDir.NoDotAndDotDot)
# If set to true items that dont match are displayed disabled
qfsm.setNameFilterDisables(False)
pext = ["*{0}".format(x) for x in project.extensions]
logger.debug(pext)
qfsm.setNameFilters(pext)
self.__projects[project_path] = project
self.__check_files_for(project_path)
self.emit(SIGNAL("projectOpened(PyQt_PyObject)"), project)
else:
qfsm = self.__projects[project_path]
return qfsm
示例7: __init__
# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import setRootPath [as 别名]
def __init__(self):
QWidget.__init__(self)
hbox = QHBoxLayout(self)
hbox.setContentsMargins(0, 0, 0, 0)
self.btnClose = QPushButton(self.style().standardIcon(QStyle.SP_DialogCloseButton), "")
self.completer = QCompleter(self)
self.pathLine = ui_tools.LineEditTabCompleter(self.completer)
fileModel = QFileSystemModel(self.completer)
fileModel.setRootPath("")
self.completer.setModel(fileModel)
self.pathLine.setCompleter(self.completer)
self.btnOpen = QPushButton(self.style().standardIcon(QStyle.SP_ArrowRight), "Open!")
hbox.addWidget(self.btnClose)
hbox.addWidget(QLabel(self.tr("Path:")))
hbox.addWidget(self.pathLine)
hbox.addWidget(self.btnOpen)
self.connect(self.pathLine, SIGNAL("returnPressed()"), self._open_file)
self.connect(self.btnOpen, SIGNAL("clicked()"), self._open_file)
示例8: load_tree
# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import setRootPath [as 别名]
def load_tree(self, project):
"""Load the tree view on the right based on the project selected."""
qfsm = QFileSystemModel()
#FIXME it's not loading the proper folder, just the root /
qfsm.setRootPath(project.path)
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)
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
示例9: __init__
# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import setRootPath [as 别名]
def __init__(self, *args):
super(FileBrowser, self).__init__(*args)
layout = QVBoxLayout()
model = QFileSystemModel()
filters = ["*.jpg", "*.JPG", "*.jpeg", "*.JPEG","*.png","*.PNG"]
model.setNameFilters(filters)
self.directoryTree = QTreeView()
self.directoryTree.setModel(model)
self.directoryTree.currentChanged = self.currentChanged
self.directoryTree.setSortingEnabled(True)
self.directoryTree.sortByColumn(0, Qt.AscendingOrder)
self.fileList = QListWidget()
layout.addWidget(self.directoryTree)
self.setLayout(layout)
root = model.setRootPath(QDir.homePath())
self.directoryTree.setRootIndex(root)
示例10: mainInitial
# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import setRootPath [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)
示例11: __init__
# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import setRootPath [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))
示例12: import
# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import setRootPath [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_())
示例13: SourceFileTreeWidget
# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import setRootPath [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)
示例14: DirectoryWidget
# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import setRootPath [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 ¤t", 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)
#.........这里部分代码省略.........
示例15: MainWindow
# 需要导入模块: from PyQt4.QtGui import QFileSystemModel [as 别名]
# 或者: from PyQt4.QtGui.QFileSystemModel import setRootPath [as 别名]
class MainWindow(QWidget):
'''
The initial method creates the window and connects the rename method.
'''
def __init__(self):
QWidget.__init__(self)
self.setWindowTitle("cuteRenamer")
#Set Data-Model for showing the directories
self.dirModel = QFileSystemModel()
self.dirModel.setRootPath('/')
self.dirModel.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)#Show only directories without '.' and '..'
#Set the view for the directories
self.dirView = QTreeView()
self.dirView.setModel(self.dirModel)
#Show only the directories in the view
self.dirView.setColumnHidden(1, True)
self.dirView.setColumnHidden(2, True)
self.dirView.setColumnHidden(3, True)
self.dirView.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
#Listedit for the optional listfile
listPathLabel = QLabel("Path to list:")
self.listPathEdit = QLineEdit()
#Start renaming with number...
startLabel = QLabel("Start (default is 1)")
self.startEdit = QLineEdit()
#LineEdit for the prefix
prefixLabel = QLabel("Prefix")
self.prefixEdit = QLineEdit()
#LineEdit for the postfix
postfixLabel = QLabel("Postfix")
self.postfixEdit = QLineEdit()
#Checkbox to conserve file extensions
self.checkboxConserve = QCheckBox("Conserve file extensions")
checkboxLayout = QHBoxLayout()
checkboxLayout.addStretch(1)
checkboxLayout.addWidget(self.checkboxConserve)
#The button to start renaming
renameButton = QPushButton('Rename!')
buttonsLayout = QHBoxLayout()
buttonsLayout.addStretch(1)
buttonsLayout.addWidget(renameButton)
vertical = QVBoxLayout()
vertical.addWidget(self.dirView)
vertical.addSpacing(10)
vertical.addWidget(listPathLabel)
vertical.addWidget(self.listPathEdit)
vertical.addSpacing(10)
vertical.addWidget(startLabel)
vertical.addWidget(self.startEdit)
vertical.addSpacing(10)
vertical.addWidget(prefixLabel)
vertical.addWidget(self.prefixEdit)
vertical.addSpacing(10)
vertical.addWidget(postfixLabel)
vertical.addWidget(self.postfixEdit)
vertical.addSpacing(10)
vertical.addLayout(checkboxLayout)
vertical.addSpacing(20)
vertical.addLayout(buttonsLayout)
self.setLayout(vertical)
#If the button is clicked start the renaming
self.connect(renameButton, SIGNAL('clicked()'), self.rename)
'''
This method prepares all options and starts the rename progress.
'''
def rename(self):
selectedIndex = self.dirView.selectedIndexes()
if self.listPathEdit.text() == "":
print "Read the whole directory"
files = os.listdir(self.dirModel.filePath(selectedIndex[0]))
elif (not self.listPathEdit.text() == "") and os.path.isfile(self.listPathEdit.text()):
print "Read filenames from %s" % self.listPathEdit.text()
files = [i.rstrip('\n') for i in open(self.listPathEdit.text(), "r")]
else:
print "Path to list doesn't exist or is not a file!"
if not self.startEdit.text() == "":
start = int(self.startEdit.text())
else:
start = 1
#.........这里部分代码省略.........