Python PyQt5.QtCore 模块,QFileInfo() 实例源码
我们从Python开源项目中,提取了以下37个代码示例,用于说明如何使用PyQt5.QtCore.QFileInfo()。
def update(self):
# Update files.
self._ui.project_tree.clear()
items = []
icon_provider = QFileIconProvider()
for cur_file in self.project.files:
file_info = QFileInfo(cur_file)
item = QTreeWidgetItem(None, [
os.path.relpath(cur_file, self.project.proj_dir),
"N/A",
])
item.setData(0, Qt.UserRole, Project.file_to_idb(cur_file))
item.setIcon(0, icon_provider.icon(file_info))
items.append(item)
self._ui.project_tree.insertTopLevelItems(0, items)
# Update other stuff.
self._ui.project_path.setText(self.project.proj_dir)
def __init__(self, fileName, parent=None):
super(TabDialog, self).__init__(parent)
fileInfo = QFileInfo(fileName)
tabWidget = QTabWidget()
tabWidget.addTab(GeneralTab(fileInfo), "General")
tabWidget.addTab(PermissionsTab(fileInfo), "Permissions")
tabWidget.addTab(ApplicationsTab(fileInfo), "Applications")
buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
buttonBox.accepted.connect(self.accept)
buttonBox.rejected.connect(self.reject)
mainLayout = QVBoxLayout()
mainLayout.addWidget(tabWidget)
mainLayout.addWidget(buttonBox)
self.setLayout(mainLayout)
self.setWindowTitle("Tab Dialog")
def __init__(self, fileName, parent=None):
super(TabDialog, self).__init__(parent)
fileInfo = QFileInfo(fileName)
tabWidget = QTabWidget()
tabWidget.addTab(GeneralTab(fileInfo), "General")
tabWidget.addTab(PermissionsTab(fileInfo), "Permissions")
tabWidget.addTab(ApplicationsTab(fileInfo), "Applications")
buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
buttonBox.accepted.connect(self.accept)
buttonBox.rejected.connect(self.reject)
mainLayout = QVBoxLayout()
mainLayout.addWidget(tabWidget)
mainLayout.addWidget(buttonBox)
self.setLayout(mainLayout)
self.setWindowTitle("Tab Dialog")
def load_file(self, filename):
file = QFile("{}/{}".format(os.getcwd(), filename))
if not file.open(QtCore.QIODevice.ReadOnly):
print("couldn't open file")
stream = QtCore.QTextStream(file)
stream.setCodec("UTF-8")
content = stream.readAll()
# built structure tree
self.ast_generator.clear_ast()
self.ast_generator.parse(mistune.preprocessing(content), filename=filename)
entry = self.ast_generator.ast
entry["time"] = QFileInfo(file).lastModified().toMSecsSinceEpoch()
# add html code to tree nodes
for i, lvl2 in enumerate(list(entry["content"])):
content_markdown = "##{}\n{}".format(lvl2["title"], lvl2["content"])
content_html = self.markdowner_simple(content_markdown)
entry["content"][i]["html"] = self.preview_css_str + content_html
return entry
def __init__(self, fileName, parent=None):
super(TabDialog, self).__init__(parent)
fileInfo = QFileInfo(fileName)
tabWidget = QTabWidget()
tabWidget.addTab(GeneralTab(fileInfo), "General")
tabWidget.addTab(PermissionsTab(fileInfo), "Permissions")
tabWidget.addTab(ApplicationsTab(fileInfo), "Applications")
buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
buttonBox.accepted.connect(self.accept)
buttonBox.rejected.connect(self.reject)
mainLayout = QVBoxLayout()
mainLayout.addWidget(tabWidget)
mainLayout.addWidget(buttonBox)
self.setLayout(mainLayout)
self.setWindowTitle("Tab Dialog")
def get_path(path: str) -> str:
prefix = sys._MEIPASS if getattr(sys, 'frozen', False) else QFileInfo(__file__).absolutePath()
return os.path.join(prefix, path)
def loadQSS(theme, devmode: bool = False) -> str:
if devmode:
filename = os.path.join(QFileInfo(__file__).absolutePath(), 'vidcutter/styles/{}.qss'.format(theme))
else:
filename = ':/styles/{}.qss'.format(theme)
if QFileInfo(filename).exists():
qssfile = QFile(filename)
qssfile.open(QFile.ReadOnly | QFile.Text)
content = QTextStream(qssfile).readAll()
qApp.setStyleSheet(content)
return content
def current_config_file(self, new_conf_file_path):
"""
Opens a new configuration file at `path new_conf_file_path`, and sets the field to that path.
If the state is dirty, this is forbidden: raises a DirtyStateException. Otherwise,
* opens the configuration file at the given conf_file_path (path = None raises a TypeError, while nonexistent
file raises a FileNotFoundError)
* replaces the current_configuration with its contents.
* remembers the file name in current_config_file
:param new_conf_file_path:
:return:
"""
self.ensure_not_dirty()
# open the file and read the new current configuration
print("Opening configuration file : '" + new_conf_file_path + "'")
with open(new_conf_file_path, 'r') as f:
self.current_configuration = GlobalEnvsConfig.from_yaml(f)
# keep a backup for 'cancel'
self.current_configuration_bak = deepcopy(self.current_configuration)
# remember the new file path - use the private field not the property
self._current_config_file = new_conf_file_path
# alert of the changes
self.signals.current_file_changed.emit() # QFileInfo(new_conf_file_path)
self.signals.current_config_changed_or_saved.emit(None)
def rslot_current_file_changed(self): # , file: QFileInfo=None
"""
This right slot should be called whenever the file has been changed.
We have to recreate the tabs view and update the title bar
:return:
"""
with PopupOnError(self):
# refresh if needed
self.refresh_view_on_file_change()
# refresh the title bar
self.setWindowFilePath(self.get_current_file())
def downloadFile(self):
self.url = QUrl(self.urlLineEdit.text())
fileInfo = QFileInfo(self.url.path())
fileName = fileInfo.fileName()
if not fileName:
fileName = 'index.html'
if QFile.exists(fileName):
ret = QMessageBox.question(self, "HTTP",
"There already exists a file called %s in the current "
"directory. Overwrite?" % fileName,
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if ret == QMessageBox.No:
return
QFile.remove(fileName)
self.outFile = QFile(fileName)
if not self.outFile.open(QIODevice.WriteOnly):
QMessageBox.information(self, "HTTP",
"Unable to save the file %s: %s." % (fileName, self.outFile.errorString()))
self.outFile = None
return
self.progressDialog.setWindowTitle("HTTP")
self.progressDialog.setLabelText("Downloading %s." % fileName)
self.downloadButton.setEnabled(False)
self.httpRequestAborted = False
self.startRequest(self.url)
def setCurrentFileName(self, fileName=''):
self.fileName = fileName
self.textEdit.document().setModified(False)
if not fileName:
shownName = 'untitled.txt'
else:
shownName = QFileInfo(fileName).fileName()
self.setWindowTitle(self.tr("%s[*] - %s" % (shownName, "Rich Text")))
self.setWindowModified(False)
def filePrintPdf(self):
fn, _ = QFileDialog.getSaveFileName(self, "Export PDF", None,
"PDF files (*.pdf);;All Files (*)")
if fn:
if QFileInfo(fn).suffix().isEmpty():
fn += '.pdf'
printer = QPrinter(QPrinter.HighResolution)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName(fn)
self.textEdit.document().print_(printer)
def addImage(self):
fileNames, _ = QFileDialog.getOpenFileNames(self, "Open Images", '',
"Images (*.png *.xpm *.jpg);;All Files (*)")
for fileName in fileNames:
row = self.imagesTable.rowCount()
self.imagesTable.setRowCount(row + 1)
imageName = QFileInfo(fileName).baseName()
item0 = QTableWidgetItem(imageName)
item0.setData(Qt.UserRole, fileName)
item0.setFlags(item0.flags() & ~Qt.ItemIsEditable)
item1 = QTableWidgetItem("Normal")
item2 = QTableWidgetItem("Off")
if self.guessModeStateAct.isChecked():
if '_act' in fileName:
item1.setText("Active")
elif '_dis' in fileName:
item1.setText("Disabled")
elif '_sel' in fileName:
item1.setText("Selected")
if '_on' in fileName:
item2.setText("On")
self.imagesTable.setItem(row, 0, item0)
self.imagesTable.setItem(row, 1, item1)
self.imagesTable.setItem(row, 2, item2)
self.imagesTable.openPersistentEditor(item1)
self.imagesTable.openPersistentEditor(item2)
item0.setCheckState(Qt.Checked)
def openFile(self, fileName):
self.currentMovieDirectory = QFileInfo(fileName).path()
self.movie.stop()
self.movieLabel.setMovie(self.movie)
self.movie.setFileName(fileName)
self.movie.start()
self.updateFrameSlider();
self.updateButtons();
def strippedName(self, fullFileName):
return QFileInfo(fullFileName).fileName()
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.imagesDir = QFileInfo(__file__).absolutePath() + '/images'
self.updateTimer = QTimer(self)
self.demoStartTime = QTime()
self.fpsTime = QTime()
self.background = QPixmap()
self.scene = None
self.mainSceneRoot = None
self.frameTimeList = []
self.fpsHistory = []
self.currentFps = Colors.fps
self.fpsMedian = -1
self.fpsLabel = None
self.pausedLabel = None
self.doneAdapt = False
self.useTimer = False
self.updateTimer.setSingleShot(True)
self.companyLogo = None
self.qtLogo = None
self.setupWidget()
self.setupScene()
self.setupSceneItems()
self.drawBackgroundToPixmap()
def __init__(self, el, parent=None):
super(MenuContentItem, self).__init__(parent)
self.name = el.getAttribute('name')
self.heading = None
self.description1 = None
self.description2 = None
readme_dir = QFileInfo(__file__).dir()
readme_dir.cdUp()
readme_dir.cd(el.getAttribute('dirname'))
self.readmePath = readme_dir.absoluteFilePath('README')
self._prepared = False
def downloadFile(self):
self.url = QUrl(self.urlLineEdit.text())
fileInfo = QFileInfo(self.url.path())
fileName = fileInfo.fileName()
if not fileName:
fileName = 'index.html'
if QFile.exists(fileName):
ret = QMessageBox.question(self, "HTTP",
"There already exists a file called %s in the current "
"directory. Overwrite?" % fileName,
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if ret == QMessageBox.No:
return
QFile.remove(fileName)
self.outFile = QFile(fileName)
if not self.outFile.open(QIODevice.WriteOnly):
QMessageBox.information(self, "HTTP",
"Unable to save the file %s: %s." % (fileName, self.outFile.errorString()))
self.outFile = None
return
self.progressDialog.setWindowTitle("HTTP")
self.progressDialog.setLabelText("Downloading %s." % fileName)
self.downloadButton.setEnabled(False)
self.httpRequestAborted = False
self.startRequest(self.url)
def setCurrentFileName(self, fileName=''):
self.fileName = fileName
self.textEdit.document().setModified(False)
if not fileName:
shownName = 'untitled.txt'
else:
shownName = QFileInfo(fileName).fileName()
self.setWindowTitle(self.tr("%s[*] - %s" % (shownName, "Rich Text")))
self.setWindowModified(False)
def filePrintPdf(self):
fn, _ = QFileDialog.getSaveFileName(self, "Export PDF", None,
"PDF files (*.pdf);;All Files (*)")
if fn:
if QFileInfo(fn).suffix().isEmpty():
fn += '.pdf'
printer = QPrinter(QPrinter.HighResolution)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName(fn)
self.textEdit.document().print_(printer)
def addImage(self):
fileNames, _ = QFileDialog.getOpenFileNames(self, "Open Images", '',
"Images (*.png *.xpm *.jpg);;All Files (*)")
for fileName in fileNames:
row = self.imagesTable.rowCount()
self.imagesTable.setRowCount(row + 1)
imageName = QFileInfo(fileName).baseName()
item0 = QTableWidgetItem(imageName)
item0.setData(Qt.UserRole, fileName)
item0.setFlags(item0.flags() & ~Qt.ItemIsEditable)
item1 = QTableWidgetItem("Normal")
item2 = QTableWidgetItem("Off")
if self.guessModeStateAct.isChecked():
if '_act' in fileName:
item1.setText("Active")
elif '_dis' in fileName:
item1.setText("Disabled")
elif '_sel' in fileName:
item1.setText("Selected")
if '_on' in fileName:
item2.setText("On")
self.imagesTable.setItem(row, 0, item0)
self.imagesTable.setItem(row, 1, item1)
self.imagesTable.setItem(row, 2, item2)
self.imagesTable.openPersistentEditor(item1)
self.imagesTable.openPersistentEditor(item2)
item0.setCheckState(Qt.Checked)
def openFile(self, fileName):
self.currentMovieDirectory = QFileInfo(fileName).path()
self.movie.stop()
self.movieLabel.setMovie(self.movie)
self.movie.setFileName(fileName)
self.movie.start()
self.updateFrameSlider();
self.updateButtons();
def strippedName(self, fullFileName):
return QFileInfo(fullFileName).fileName()
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.imagesDir = QFileInfo(__file__).absolutePath() + '/images'
self.updateTimer = QTimer(self)
self.demoStartTime = QTime()
self.fpsTime = QTime()
self.background = QPixmap()
self.scene = None
self.mainSceneRoot = None
self.frameTimeList = []
self.fpsHistory = []
self.currentFps = Colors.fps
self.fpsMedian = -1
self.fpsLabel = None
self.pausedLabel = None
self.doneAdapt = False
self.useTimer = False
self.updateTimer.setSingleShot(True)
self.companyLogo = None
self.qtLogo = None
self.setupWidget()
self.setupScene()
self.setupSceneItems()
self.drawBackgroundToPixmap()
def __init__(self, el, parent=None):
super(MenuContentItem, self).__init__(parent)
self.name = el.getAttribute('name')
self.heading = None
self.description1 = None
self.description2 = None
readme_dir = QFileInfo(__file__).dir()
readme_dir.cdUp()
readme_dir.cd(el.getAttribute('dirname'))
self.readmePath = readme_dir.absoluteFilePath('README')
self._prepared = False
def icon(self, arg):
if isinstance(arg, QFileInfo):
if (arg.isDir() and os.path.isfile(os.path.join(arg.filePath(), constants.PROJECT_FILE))) \
or (arg.isFile() and arg.fileName() == constants.PROJECT_FILE):
return QIcon(":/icons/icons/appicon.png")
return super().icon(arg)
def downloadFile(self):
self.url = QUrl(self.urlLineEdit.text())
fileInfo = QFileInfo(self.url.path())
fileName = fileInfo.fileName()
if not fileName:
fileName = 'index.html'
if QFile.exists(fileName):
ret = QMessageBox.question(self, "HTTP",
"There already exists a file called %s in the current "
"directory. Overwrite?" % fileName,
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if ret == QMessageBox.No:
return
QFile.remove(fileName)
self.outFile = QFile(fileName)
if not self.outFile.open(QIODevice.WriteOnly):
QMessageBox.information(self, "HTTP",
"Unable to save the file %s: %s." % (fileName, self.outFile.errorString()))
self.outFile = None
return
self.progressDialog.setWindowTitle("HTTP")
self.progressDialog.setLabelText("Downloading %s." % fileName)
self.downloadButton.setEnabled(False)
self.httpRequestAborted = False
self.startRequest(self.url)
def setCurrentFileName(self, fileName=''):
self.fileName = fileName
self.textEdit.document().setModified(False)
if not fileName:
shownName = 'untitled.txt'
else:
shownName = QFileInfo(fileName).fileName()
self.setWindowTitle(self.tr("%s[*] - %s" % (shownName, "Rich Text")))
self.setWindowModified(False)
def filePrintPdf(self):
fn, _ = QFileDialog.getSaveFileName(self, "Export PDF", None,
"PDF files (*.pdf);;All Files (*)")
if fn:
if QFileInfo(fn).suffix().isEmpty():
fn += '.pdf'
printer = QPrinter(QPrinter.HighResolution)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName(fn)
self.textEdit.document().print_(printer)
def addImage(self):
fileNames, _ = QFileDialog.getOpenFileNames(self, "Open Images", '',
"Images (*.png *.xpm *.jpg);;All Files (*)")
for fileName in fileNames:
row = self.imagesTable.rowCount()
self.imagesTable.setRowCount(row + 1)
imageName = QFileInfo(fileName).baseName()
item0 = QTableWidgetItem(imageName)
item0.setData(Qt.UserRole, fileName)
item0.setFlags(item0.flags() & ~Qt.ItemIsEditable)
item1 = QTableWidgetItem("Normal")
item2 = QTableWidgetItem("Off")
if self.guessModeStateAct.isChecked():
if '_act' in fileName:
item1.setText("Active")
elif '_dis' in fileName:
item1.setText("Disabled")
elif '_sel' in fileName:
item1.setText("Selected")
if '_on' in fileName:
item2.setText("On")
self.imagesTable.setItem(row, 0, item0)
self.imagesTable.setItem(row, 1, item1)
self.imagesTable.setItem(row, 2, item2)
self.imagesTable.openPersistentEditor(item1)
self.imagesTable.openPersistentEditor(item2)
item0.setCheckState(Qt.Checked)
def openFile(self, fileName):
self.currentMovieDirectory = QFileInfo(fileName).path()
self.movie.stop()
self.movieLabel.setMovie(self.movie)
self.movie.setFileName(fileName)
self.movie.start()
self.updateFrameSlider();
self.updateButtons();
def strippedName(self, fullFileName):
return QFileInfo(fullFileName).fileName()
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.imagesDir = QFileInfo(__file__).absolutePath() + '/images'
self.updateTimer = QTimer(self)
self.demoStartTime = QTime()
self.fpsTime = QTime()
self.background = QPixmap()
self.scene = None
self.mainSceneRoot = None
self.frameTimeList = []
self.fpsHistory = []
self.currentFps = Colors.fps
self.fpsMedian = -1
self.fpsLabel = None
self.pausedLabel = None
self.doneAdapt = False
self.useTimer = False
self.updateTimer.setSingleShot(True)
self.companyLogo = None
self.qtLogo = None
self.setupWidget()
self.setupScene()
self.setupSceneItems()
self.drawBackgroundToPixmap()
def __init__(self, el, parent=None):
super(MenuContentItem, self).__init__(parent)
self.name = el.getAttribute('name')
self.heading = None
self.description1 = None
self.description2 = None
readme_dir = QFileInfo(__file__).dir()
readme_dir.cdUp()
readme_dir.cd(el.getAttribute('dirname'))
self.readmePath = readme_dir.absoluteFilePath('README')
self._prepared = False
def httpFinished(self):
if self.httpRequestAborted:
if self.outFile is not None:
self.outFile.close()
self.outFile.remove()
self.outFile = None
self.reply.deleteLater()
self.reply = None
self.progressDialog.hide()
return
self.progressDialog.hide()
self.outFile.flush()
self.outFile.close()
redirectionTarget = self.reply.attribute(QNetworkRequest.RedirectionTargetAttribute)
if self.reply.error():
self.outFile.remove()
QMessageBox.information(self, "HTTP",
"Download failed: %s." % self.reply.errorString())
self.downloadButton.setEnabled(True)
elif redirectionTarget is not None:
newUrl = self.url.resolved(redirectionTarget)
ret = QMessageBox.question(self, "HTTP",
"Redirect to %s?" % newUrl.toString(),
QMessageBox.Yes | QMessageBox.No)
if ret == QMessageBox.Yes:
self.url = newUrl
self.reply.deleteLater()
self.reply = None
self.outFile.open(QIODevice.WriteOnly)
self.outFile.resize(0)
self.startRequest(self.url)
return
else:
fileName = QFileInfo(QUrl(self.urlLineEdit.text()).path()).fileName()
self.statusLabel.setText("Downloaded %s to %s." % (fileName, QDir.currentPath()))
self.downloadButton.setEnabled(True)
self.reply.deleteLater()
self.reply = None
self.outFile = None
def httpFinished(self):
if self.httpRequestAborted:
if self.outFile is not None:
self.outFile.close()
self.outFile.remove()
self.outFile = None
self.reply.deleteLater()
self.reply = None
self.progressDialog.hide()
return
self.progressDialog.hide()
self.outFile.flush()
self.outFile.close()
redirectionTarget = self.reply.attribute(QNetworkRequest.RedirectionTargetAttribute)
if self.reply.error():
self.outFile.remove()
QMessageBox.information(self, "HTTP",
"Download failed: %s." % self.reply.errorString())
self.downloadButton.setEnabled(True)
elif redirectionTarget is not None:
newUrl = self.url.resolved(redirectionTarget)
ret = QMessageBox.question(self, "HTTP",
"Redirect to %s?" % newUrl.toString(),
QMessageBox.Yes | QMessageBox.No)
if ret == QMessageBox.Yes:
self.url = newUrl
self.reply.deleteLater()
self.reply = None
self.outFile.open(QIODevice.WriteOnly)
self.outFile.resize(0)
self.startRequest(self.url)
return
else:
fileName = QFileInfo(QUrl(self.urlLineEdit.text()).path()).fileName()
self.statusLabel.setText("Downloaded %s to %s." % (fileName, QDir.currentPath()))
self.downloadButton.setEnabled(True)
self.reply.deleteLater()
self.reply = None
self.outFile = None
def httpFinished(self):
if self.httpRequestAborted:
if self.outFile is not None:
self.outFile.close()
self.outFile.remove()
self.outFile = None
self.reply.deleteLater()
self.reply = None
self.progressDialog.hide()
return
self.progressDialog.hide()
self.outFile.flush()
self.outFile.close()
redirectionTarget = self.reply.attribute(QNetworkRequest.RedirectionTargetAttribute)
if self.reply.error():
self.outFile.remove()
QMessageBox.information(self, "HTTP",
"Download failed: %s." % self.reply.errorString())
self.downloadButton.setEnabled(True)
elif redirectionTarget is not None:
newUrl = self.url.resolved(redirectionTarget)
ret = QMessageBox.question(self, "HTTP",
"Redirect to %s?" % newUrl.toString(),
QMessageBox.Yes | QMessageBox.No)
if ret == QMessageBox.Yes:
self.url = newUrl
self.reply.deleteLater()
self.reply = None
self.outFile.open(QIODevice.WriteOnly)
self.outFile.resize(0)
self.startRequest(self.url)
return
else:
fileName = QFileInfo(QUrl(self.urlLineEdit.text()).path()).fileName()
self.statusLabel.setText("Downloaded %s to %s." % (fileName, QDir.currentPath()))
self.downloadButton.setEnabled(True)
self.reply.deleteLater()
self.reply = None
self.outFile = None