zoukankan      html  css  js  c++  java
  • Python_PyQt5_打开文件并修改字体

    在同文件夹下新建一个 测试文档.txt  再运行下面代码,可以实现效果

    代码

     1 #!Python3
     2 # -*- coding:utf-8 -*-
     3 
     4 """
     5 目标:主窗口打开文本文件,修改字体
     6 
     7 文本编辑控件和一个状态栏
     8 """
     9 
    10 import sys
    11 from PyQt5.QtWidgets import QApplication,QMainWindow,QTextEdit,QAction,QFileDialog,QFontDialog
    12 from PyQt5.QtGui import QIcon
    13 
    14 class Example (QMainWindow):
    15     def __init__(self):
    16         super().__init__()
    17         self.initUI()
    18 
    19     def initUI(self):
    20         self.textEdit = QTextEdit()
    21         self.setCentralWidget(self.textEdit)
    22         self.statusBar()
    23 
    24         #打开文件
    25         openFile = QAction(QIcon("打开ico.ico"),"打开",self)
    26         #定义快捷键
    27         openFile.setShortcut("Ctrl+o")
    28         openFile.setStatusTip("打开一个文件") #提示语
    29         #发送信号
    30         openFile.triggered.connect(self.showDialog)
    31         
    32         #改字体
    33         chengFont = QAction(QIcon("设置字体ico.ico"),"设置字体",self)
    34         #定义快捷键
    35         chengFont.setShortcut("Ctrl+A")
    36         chengFont.setStatusTip("设置字体") #提示语
    37         #发送信号
    38         chengFont.triggered.connect(self.chengeFont) 
    39 
    40         
    41         #实例化菜单栏
    42         menubar = self.menuBar()
    43         #创建菜单
    44         fileMenu = menubar.addMenu("&打开文件")
    45         fileMenu.addAction(openFile)
    46         fileMenu = menubar.addMenu("&设置字体")
    47         fileMenu.addAction(chengFont)
    48         
    49         self.setGeometry(300,300,350,300)
    50         self.setWindowTitle("打开文件并修改字体")
    51         self.show()
    52 
    53     def showDialog(self):
    54         fname = QFileDialog.getOpenFileName(self,"打开文件",".") #打开文件当前文件夹下的文件
    55         if fname[0]:
    56             with open(fname[0],'r') as f:
    57                 data = f.read()
    58                 self.textEdit.setText(str(data))
    59 
    60     def chengeFont(self):
    61         font,ok =QFontDialog.getFont()
    62         if ok:
    63             self.textEdit.setFont(font)     #打开测试文档里的 
    64         
    65 if __name__ == "__main__" :
    66     app = QApplication(sys.argv)
    67     ex = Example()
    68     sys.exit(app.exec_())
    PyQt5窗口打开txt文件并设置字体
  • 相关阅读:
    BOM 事件 navigator浏览器的判断
    闭包
    超简单超实用的走马灯效果实现
    对DOM的增删改查
    SVN版本回退与常用命令总结
    mongodb使用总结
    如何理解 IE 的文档兼容模式
    软件开发编码规范
    第一篇绑定数据 CMS
    关于IIS7.5下的web.config配置的一些问题
  • 原文地址:https://www.cnblogs.com/hellangels333/p/8249961.html
Copyright © 2011-2022 走看看