Python PyQt5.QtCore 模块,QFile() 实例源码
我们从Python开源项目中,提取了以下27个代码示例,用于说明如何使用PyQt5.QtCore.QFile()。
def main(args=[],app=None):
'''
Default main program which starts Qt based on the command line arguments `args', sets the stylesheet if present, then
creates the window object and shows it. The `args' list of command line arguments is also passed to the window object
to pick up on specified directories. The `app' object would be the QApplication object if this was created elsewhere,
otherwise it's created here. Returns the value of QApplication.exec_() if this object was created here otherwise 0.
'''
if not app:
app = QtGui.QApplication(args)
app.setAttribute(Qt.AA_DontUseNativeMenuBar) # in OSX, forces menubar to be in window
app.setStyle('Plastique')
# load the stylesheet included as a Qt resource
with closing(QtCore.QFile(':/css/DefaultUIStyle.css')) as f:
if f.open(QtCore.QFile.ReadOnly):
app.setStyleSheet(bytes(f.readAll()).decode('UTF-8'))
else:
print('Failed to read %r'%f.fileName())
browser=DicomBrowser(args)
browser.show()
return app.exec_() if app else 0
def __init__(self, subtitle, encoding="UTF-8"):
super().__init__()
subtitlefile = QFile(subtitle)
if not subtitlefile.open(QIODevice.ReadOnly | QIODevice.Text):
return
text = QTextStream(subtitlefile)
text.setCodec(encoding)
subtitletext = text.readAll()
# ('s?ra', 'saat', 'dakika', 'saniye', 'milisaniye', 'saat', 'dakika', 'saniye', 'milisaniye', 'birincisat?r', 'ikincisat?r')
compile = re.compile(r"(\d.*)\n(\d{2}):(\d{2}):(\d{2}),(\d{3}) --> (\d{2}):(\d{2}):(\d{2}),(\d{3})\n(\W.*|\w.*)\n(\w*|\W*|\w.*|\W.*)\n")
self.sublist = compile.findall(subtitletext)
def openFile(self):
filePath, _ = QFileDialog.getOpenFileName(self, "Open File",
self.xmlPath, "XML files (*.xml);;HTML files (*.html);;"
"SVG files (*.svg);;User Interface files (*.ui)")
if filePath:
f = QFile(filePath)
if f.open(QIODevice.ReadOnly):
document = QDomDocument()
if document.setContent(f):
newModel = DomModel(document, self)
self.view.setModel(newModel)
self.model = newModel
self.xmlPath = filePath
f.close()
def insertTextObject(self):
fileName = self.fileNameLineEdit.text()
file = QFile(fileName)
if not file.open(QIODevice.ReadOnly):
QMessageBox.warning(self, "Error Opening File",
"Could not open '%s'" % fileName)
svgData = file.readAll()
svgCharFormat = QTextCharFormat()
svgCharFormat.setObjectType(Window.SvgTextFormat)
svgCharFormat.setProperty(Window.SvgData, svgData)
try:
# Python v2.
orc = unichr(0xfffc)
except NameError:
# Python v3.
orc = chr(0xfffc)
cursor = self.textEdit.textCursor()
cursor.insertText(orc, svgCharFormat)
self.textEdit.setTextCursor(cursor)
def __init__(self, parent=None):
super(DragWidget, self).__init__(parent)
dictionaryFile = QFile(':/dictionary/words.txt')
dictionaryFile.open(QIODevice.ReadOnly)
x = 5
y = 5
for word in QTextStream(dictionaryFile).readAll().split():
wordLabel = DragLabel(word, self)
wordLabel.move(x, y)
wordLabel.show()
x += wordLabel.width() + 2
if x >= 195:
x = 5
y += wordLabel.height() + 2
newPalette = self.palette()
newPalette.setColor(QPalette.Window, Qt.white)
self.setPalette(newPalette)
self.setAcceptDrops(True)
self.setMinimumSize(400, max(200, y))
self.setWindowTitle("Draggable Text")
def openFile(self):
filePath, _ = QFileDialog.getOpenFileName(self, "Open File",
self.xmlPath, "XML files (*.xml);;HTML files (*.html);;"
"SVG files (*.svg);;User Interface files (*.ui)")
if filePath:
f = QFile(filePath)
if f.open(QIODevice.ReadOnly):
document = QDomDocument()
if document.setContent(f):
newModel = DomModel(document, self)
self.view.setModel(newModel)
self.model = newModel
self.xmlPath = filePath
f.close()
def insertTextObject(self):
fileName = self.fileNameLineEdit.text()
file = QFile(fileName)
if not file.open(QIODevice.ReadOnly):
QMessageBox.warning(self, "Error Opening File",
"Could not open '%s'" % fileName)
svgData = file.readAll()
svgCharFormat = QTextCharFormat()
svgCharFormat.setObjectType(Window.SvgTextFormat)
svgCharFormat.setProperty(Window.SvgData, svgData)
try:
# Python v2.
orc = unichr(0xfffc)
except NameError:
# Python v3.
orc = chr(0xfffc)
cursor = self.textEdit.textCursor()
cursor.insertText(orc, svgCharFormat)
self.textEdit.setTextCursor(cursor)
def __init__(self, parent=None):
super(DragWidget, self).__init__(parent)
dictionaryFile = QFile(':/dictionary/words.txt')
dictionaryFile.open(QIODevice.ReadOnly)
x = 5
y = 5
for word in QTextStream(dictionaryFile).readAll().split():
wordLabel = DragLabel(word, self)
wordLabel.move(x, y)
wordLabel.show()
x += wordLabel.width() + 2
if x >= 195:
x = 5
y += wordLabel.height() + 2
newPalette = self.palette()
newPalette.setColor(QPalette.Window, Qt.white)
self.setPalette(newPalette)
self.setAcceptDrops(True)
self.setMinimumSize(400, max(200, y))
self.setWindowTitle("Draggable Text")
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 openFile(self):
filePath, _ = QFileDialog.getOpenFileName(self, "Open File",
self.xmlPath, "XML files (*.xml);;HTML files (*.html);;"
"SVG files (*.svg);;User Interface files (*.ui)")
if filePath:
f = QFile(filePath)
if f.open(QIODevice.ReadOnly):
document = QDomDocument()
if document.setContent(f):
newModel = DomModel(document, self)
self.view.setModel(newModel)
self.model = newModel
self.xmlPath = filePath
f.close()
def insertTextObject(self):
fileName = self.fileNameLineEdit.text()
file = QFile(fileName)
if not file.open(QIODevice.ReadOnly):
QMessageBox.warning(self, "Error Opening File",
"Could not open '%s'" % fileName)
svgData = file.readAll()
svgCharFormat = QTextCharFormat()
svgCharFormat.setObjectType(Window.SvgTextFormat)
svgCharFormat.setProperty(Window.SvgData, svgData)
try:
# Python v2.
orc = unichr(0xfffc)
except NameError:
# Python v3.
orc = chr(0xfffc)
cursor = self.textEdit.textCursor()
cursor.insertText(orc, svgCharFormat)
self.textEdit.setTextCursor(cursor)
def __init__(self, parent=None):
super(DragWidget, self).__init__(parent)
dictionaryFile = QFile(':/dictionary/words.txt')
dictionaryFile.open(QIODevice.ReadOnly)
x = 5
y = 5
for word in QTextStream(dictionaryFile).readAll().split():
wordLabel = DragLabel(word, self)
wordLabel.move(x, y)
wordLabel.show()
x += wordLabel.width() + 2
if x >= 195:
x = 5
y += wordLabel.height() + 2
newPalette = self.palette()
newPalette.setColor(QPalette.Window, Qt.white)
self.setPalette(newPalette)
self.setAcceptDrops(True)
self.setMinimumSize(400, max(200, y))
self.setWindowTitle("Draggable Text")
def __init__(self, parent=None):
super().__init__(parent)
self.setReadOnly(True)
self.setWindowTitle('About')
self.setOpenExternalLinks(True)
file = QtCore.QFile('resources/about.html')
file.open(QtCore.QFile.ReadOnly)
html = bytes(file.readAll()).decode('utf-8')
self.insertHtml(html)
def load_qss(self, theme):
path = 'resources/themes/{}/style.qss'.format(theme)
file = QtCore.QFile(path)
file.open(QtCore.QFile.ReadOnly)
ss = bytes(file.readAll()).decode('latin-1')
app = QtCore.QCoreApplication.instance()
app.setStyleSheet(ss)
self.current = ss
def readStyleSheet(self,fileName):
css=None
file = QFile(fileName)
if file.open(QIODevice.ReadOnly) :
css = file.readAll()
file.close()
return css
def readStyleSheet(self,fileName):
css=None
file = QFile(fileName)
if file.open(QIODevice.ReadOnly) :
css = file.readAll()
file.close()
return css
def readStyleSheet(self,fileName):
file = QFile(fileName)
if file.open(QIODevice.ReadOnly) :
css = file.readAll()
file.close()
return css
def readStyleSheet(self,fileName):
css=None
file = QFile(fileName)
if file.open(QIODevice.ReadOnly) :
css = file.readAll()
file.close()
return css
def open(self):
fileName, _ = QFileDialog.getOpenFileName(self)
if fileName:
fd = QFile(fileName)
if not fd.open(QIODevice.ReadOnly):
QMessageBox.information(self, "Unable to open file",
fd.errorString())
return
output = QTextStream(fd).readAll()
# Display contents.
self.centralWidget.plainTextEdit.setPlainText(output)
self.centralWidget.setBaseUrl(QUrl.fromLocalFile(fileName))
def save(self):
content = self.centralWidget.plainTextEdit.toPlainText()
fileName, _ = QFileDialog.getSaveFileName(self)
if fileName:
fd = QFile(fileName)
if not fd.open(QIODevice.WriteOnly):
QMessageBox.information(self, "Unable to open file",
fd.errorString())
return
QTextStream(fd) << content
def open(self):
fileName, _ = QFileDialog.getOpenFileName(self)
if fileName:
fd = QFile(fileName)
if not fd.open(QIODevice.ReadOnly):
QMessageBox.information(self, "Unable to open file",
fd.errorString())
return
output = QTextStream(fd).readAll()
# Display contents.
self.centralWidget.plainTextEdit.setPlainText(output)
self.centralWidget.setBaseUrl(QUrl.fromLocalFile(fileName))
def save(self):
content = self.centralWidget.plainTextEdit.toPlainText()
fileName, _ = QFileDialog.getSaveFileName(self)
if fileName:
fd = QFile(fileName)
if not fd.open(QIODevice.WriteOnly):
QMessageBox.information(self, "Unable to open file",
fd.errorString())
return
QTextStream(fd) << content
def open(self):
fileName, _ = QFileDialog.getOpenFileName(self)
if fileName:
fd = QFile(fileName)
if not fd.open(QIODevice.ReadOnly):
QMessageBox.information(self, "Unable to open file",
fd.errorString())
return
output = QTextStream(fd).readAll()
# Display contents.
self.centralWidget.plainTextEdit.setPlainText(output)
self.centralWidget.setBaseUrl(QUrl.fromLocalFile(fileName))
def save(self):
content = self.centralWidget.plainTextEdit.toPlainText()
fileName, _ = QFileDialog.getSaveFileName(self)
if fileName:
fd = QFile(fileName)
if not fd.open(QIODevice.WriteOnly):
QMessageBox.information(self, "Unable to open file",
fd.errorString())
return
QTextStream(fd) << content
def exportAsVCard(self):
name = str(self.nameLine.text())
address = self.addressText.toPlainText()
nameList = name.split()
if len(nameList) > 1:
firstName = nameList[0]
lastName = nameList[-1]
else:
firstName = name
lastName = ''
fileName, _ = QFileDialog.getSaveFileName(self, "Export Contact", '',
"vCard Files (*.vcf);;All Files (*)")
if not fileName:
return
out_file = QFile(fileName)
if not out_file.open(QIODevice.WriteOnly):
QMessageBox.information(self, "Unable to open file",
out_file.errorString())
return
out_s = QTextStream(out_file)
out_s << 'BEGIN:VCARD' << '\n'
out_s << 'VERSION:2.1' << '\n'
out_s << 'N:' << lastName << ';' << firstName << '\n'
out_s << 'FN:' << ' '.join(nameList) << '\n'
address.replace(';', '\\;')
address.replace('\n', ';')
address.replace(',', ' ')
out_s << 'ADR;HOME:;' << address << '\n'
out_s << 'END:VCARD' << '\n'
QMessageBox.information(self, "Export Successful",
"\"%s\" has been exported as a vCard." % name)
def exportAsVCard(self):
name = str(self.nameLine.text())
address = self.addressText.toPlainText()
nameList = name.split()
if len(nameList) > 1:
firstName = nameList[0]
lastName = nameList[-1]
else:
firstName = name
lastName = ''
fileName, _ = QFileDialog.getSaveFileName(self, "Export Contact", '',
"vCard Files (*.vcf);;All Files (*)")
if not fileName:
return
out_file = QFile(fileName)
if not out_file.open(QIODevice.WriteOnly):
QMessageBox.information(self, "Unable to open file",
out_file.errorString())
return
out_s = QTextStream(out_file)
out_s << 'BEGIN:VCARD' << '\n'
out_s << 'VERSION:2.1' << '\n'
out_s << 'N:' << lastName << ';' << firstName << '\n'
out_s << 'FN:' << ' '.join(nameList) << '\n'
address.replace(';', '\\;')
address.replace('\n', ';')
address.replace(',', ' ')
out_s << 'ADR;HOME:;' << address << '\n'
out_s << 'END:VCARD' << '\n'
QMessageBox.information(self, "Export Successful",
"\"%s\" has been exported as a vCard." % name)
def exportAsVCard(self):
name = str(self.nameLine.text())
address = self.addressText.toPlainText()
nameList = name.split()
if len(nameList) > 1:
firstName = nameList[0]
lastName = nameList[-1]
else:
firstName = name
lastName = ''
fileName, _ = QFileDialog.getSaveFileName(self, "Export Contact", '',
"vCard Files (*.vcf);;All Files (*)")
if not fileName:
return
out_file = QFile(fileName)
if not out_file.open(QIODevice.WriteOnly):
QMessageBox.information(self, "Unable to open file",
out_file.errorString())
return
out_s = QTextStream(out_file)
out_s << 'BEGIN:VCARD' << '\n'
out_s << 'VERSION:2.1' << '\n'
out_s << 'N:' << lastName << ';' << firstName << '\n'
out_s << 'FN:' << ' '.join(nameList) << '\n'
address.replace(';', '\\;')
address.replace('\n', ';')
address.replace(',', ' ')
out_s << 'ADR;HOME:;' << address << '\n'
out_s << 'END:VCARD' << '\n'
QMessageBox.information(self, "Export Successful",
"\"%s\" has been exported as a vCard." % name)