PyQt之 QFileDialog + QWebEngineView

QFileDialog

基于文件读写的需要,我们需要了解QFileDialog的使用

以下代码结合lineEdit,演示文件读写的基本功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
self.textEdit = QTextEdit()  # 创建文本框用于显示

def open_code(self):
filename = QFileDialog.getOpenFileName(self, 'Open file', '.')[0]
with open(filename, 'r') as f:
data = f.read()
self.textEdit.setText(data)

def clear_code(self):
self.textEdit.clear()

def save_code(self):
data=self.textEdit.toPlainText()
filename = QFileDialog.getSaveFileName(self, 'Open file', '.')[0]
with open(filename, 'w') as f:
f.write(data)

注意,读写中文文本时,需要注意编码,例如添加encoding='utf-8'

QWebEngineView

QWebEngineView可以在QT内嵌入网页,下面给一个最简单的例子,实现网易云音乐的嵌入:

1
2
3
4
5
class Player(QWebEngineView):
def __init__(self, par):
super().__init__(par)

self.load(QUrl("https://music.163.com/outchain/player?type=1&id=35631522&auto=1&height=430"))

效果如下:

0831-1

除了嵌入URL,还可以嵌入本地的页面

1
2
3
# 本地html路径
self.editor_index = (os.path.split(os.path.realpath(__file__))[0]) + "/XXX.html"
self.load(QUrl.fromLocalFile(self.editor_index))

如果在嵌入的网页中打开新的页面,需要:

1
2
3
4
5
# 重写createeditor()
def createEditor(self, QWebEnginePage_WebWindowType):
new_editor = Editor(self.mainwindow)
self.mainwindow.create_tab(new_editor)
return new_editor
不要打赏,只求关注呀QAQ