import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QDesktopServices
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("文件打开示例")
self.setGeometry(100, 100, 300, 200)
# 创建按钮
self.button = QPushButton("打开文件", self)
self.button.clicked.connect(self.open_file)
# 设置布局
layout = QVBoxLayout()
layout.addWidget(self.button)
container = QWidget()
container.setLayout(layout)
self.setCentralWidget(container)
def open_file(self):
# 指定要打开的文件路径
file_path = "C:/example/document.pdf" # 替换为实际文件路径
# 使用QDesktopServices打开文件
url = QUrl.fromLocalFile(file_path)
QDesktopServices.openUrl(url)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
核心就两步:
- 用
QUrl.fromLocalFile()把文件路径转成QUrl对象
- 调用
QDesktopServices.openUrl()让系统用默认程序打开
注意文件路径要写对,Windows用反斜杠要转义或者用正斜杠。这个方法会调用系统关联的默认程序,比如PDF用Acrobat、txt用记事本。
一句话总结:用QDesktopServices.openUrl()最省事。