PyQt6实战7--文本编辑器

一个简单的文本编辑器

features:

1.open 一个文件夹作为项目

2.save 保存当前窗口的内容

3.退出

4.双击文件可以打开文件内容

5.简单的python高亮

6.双击相同文件,会找到之前打开过的文件

打开一个文件夹

打开项目,双击打开文件

保存

代码:

from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import *
from PyQt6.QtCore import *
from PyQt6.QtGui import *
import sys
import os
from highlight import *class FileSystemModel(QFileSystemModel):def __init__(self, headName, parent=None):super().__init__(parent)self.headName = headName'''只显示名称,不显示类型和其他的信息'''def columnCount(self, parent=QModelIndex()):return 1#修改表头的列名def headerData(self, section: int, orientation: Qt.Orientation, role: int = ...):if orientation == Qt.Orientation.Horizontal and role == Qt.ItemDataRole.DisplayRole:return self.headNamereturn super().headerData(section, orientation, role)class TextEditor(QMainWindow):def __init__(self):super().__init__()self._initUI()self._initConnect()def _initUI(self):self.setWindowTitle('Text Editor')self.resize(800, 600)centerWidget =  QWidget()mainLayout = QHBoxLayout()self.left_file_tree = QTreeView()self.right_editor = QTabWidget()self.right_editor.setDocumentMode(True)self.right_editor.setTabsClosable(True)mainLayout.addWidget(self.left_file_tree)mainLayout.addWidget(self.right_editor)mainLayout.setSpacing(0)mainLayout.setContentsMargins(0, 0, 0, 0)mainLayout.setStretchFactor(self.left_file_tree, 1)mainLayout.setStretchFactor(self.right_editor, 4)centerWidget.setLayout(mainLayout)self.setCentralWidget(centerWidget)self._init_menu()def _init_menu(self):menubar = self.menuBar()menubar.setNativeMenuBar(False)fileMenu = menubar.addMenu('File')fileMenu.addAction('Open', self._open_folder)fileMenu.addAction('Save', self.save)fileMenu.addAction('Exit', self.close)def save(self):currentWidget = self.right_editor.currentWidget()if currentWidget:file_name = currentWidget.objectName()with open(file_name, 'w') as f:text = currentWidget.toPlainText()f.write(text)def _open_folder(self):dir = QFileDialog.getExistingDirectory(self, 'Open Folder', './')self.dir_path = dirself._init_file_tree(dir)self.right_editor.clear()def _init_file_tree(self, dir_path):dirname = os.path.basename(dir_path)self.model = FileSystemModel(dirname)self.model.setRootPath(dir_path)self.left_file_tree.setModel(self.model)#这里需要强制指定,否则显示root目录self.left_file_tree.setRootIndex(self.model.index(dir_path))def _initConnect(self):self.left_file_tree.doubleClicked.connect(self.on_file_tree_clicked)self.right_editor.tabCloseRequested.connect(self.close_current_tab)def close_current_tab(self, index):self.right_editor.removeTab(index)def on_file_tree_clicked(self, index):isDir = self.model.isDir(index)if not isDir:file_path = self.model.filePath(index)file_name = self.model.data(index)for i in range(self.right_editor.count()):tab = self.right_editor.widget(i)if tab.objectName() == file_path:self.right_editor.setCurrentIndex(i)returnfileEditor = QTextEdit()highlighter = SqlHighlighter(fileEditor.document())fileEditor.setObjectName(file_path)with open(file_path, 'r', encoding='utf-8') as f:fileEditor.setText(f.read())self.right_editor.addTab(fileEditor, file_name)self.right_editor.setCurrentIndex(self.right_editor.count()-1)def close(self):self.close()if __name__ == '__main__':app = QApplication(sys.argv)window = TextEditor()window.show()sys.exit(app.exec())
from PyQt6.QtWidgets import *
from PyQt6.QtGui import *
from PyQt6.QtCore import *def format(color, style=''):"""Return a QTextCharFormat with the given attributes."""_color = QColor()if type(color) is not str:_color.setRgb(color[0], color[1], color[2])else:_color.setNamedColor(color)_format = QTextCharFormat()_format.setForeground(_color)if 'bold' in style:_format.setFontWeight(QFont.Weight.Bold)if 'italic' in style:_format.setFontItalic(True)return _formatSTYLES = {'keyword': format([50, 50, 150], 'bold'),'operator': format([150, 150, 150]),'brace': format('darkGray'),'defclass': format([220, 220, 255], 'bold'),'string': format([20, 110, 100]),'string2': format([30, 120, 110]),'comment': format([128, 128, 128]),'self': format([150, 85, 140], 'italic'),'numbers': format([100, 150, 190]),
}class SqlHighlighter(QSyntaxHighlighter):keywords = ['def', 'return', 'for', 'in', 'while', 'if', 'elif', 'else','None', 'True', 'False', 'and', 'or', 'not', 'as', 'break','super', 'self', 'del', 'except', 'finally', 'is', 'class','lambda', 'try', 'with', 'from', 'nonlocal', 'pass', 'raise', 'assert', 'return', 'break', 'import', 'return', 'break', 'continue','yield', 'global',]braces = ['\{', '\}', '\(', '\)', '\[', '\]',]def __init__(self, document):super().__init__(document)rules = []# Keyword, operator, and brace rulesrules += [(r'\b%s\b' % w, 0, STYLES['keyword'])for w in SqlHighlighter.keywords]rules += [(r'%s' % b, 0, STYLES['brace'])for b in SqlHighlighter.braces]self.rules = [(QRegularExpression(pat), index, fmt) for (pat, index, fmt) in rules]def highlightBlock(self, text: str) -> None:"""Apply syntax highlighting to the given block of text."""# Do other syntax formattingfor expression, nth, format in self.rules:matchIterator = expression.globalMatch(text)while matchIterator.hasNext():# print(rule.pattern.pattern())match = matchIterator.next()self.setFormat(match.capturedStart(), match.capturedLength(), format)self.setCurrentBlockState(0)

代码地址:

GitHub - chunlaiqingke/Tiny-Tool

公众号

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/826297.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

雷电模拟器+python

import os import time from compare import compare #上一段代码我存为了compare.pyclass Ldconsole: #请根据自己软件的路径来console rF:\leidian\LDPlayer9\dnconsole.exe ld rF:\leidian\LDPlayer9\ld.exeadb rF:\leidian\LDPlayer9\adb.exe #这个类其实不用写的&…

CSRF漏洞

文章目录 目录 文章目录 一.什么是CSRF 二.CSRF漏洞工作原理 一.什么是CSRF CSRF(Cross-Site Request Forgery)漏洞,也被称为跨站请求伪造漏洞,是一种Web应用程序安全漏洞。当受害者在已经登录了某个网站的情况下,访问…

密码学 | 数字签名方法:Schnorr 签名

⚠️原文:Introduction to Schnorr Signatures ⚠️写在前面:适用于有一点密码学基础的亲故,否则建议跑路。 1 Schnorr 签名的定义 假设你有密钥对 ( x , X x ∗ G ) ( x, X x * G ) (x,Xx∗G),那么消息 m m m 的 Schnor…

吴恩达机器学习笔记 三十五 异常检测与监督学习

什么时候选择异常检测? 正样本 ( y 1 ) 的数量非常少 负样本 ( y 0 ) 的数量非常多 有很多不同的异常,现有的算法不能从正样本中得知什么是异常,或未来可能出现完全没见过的异常情况。 例如金融欺诈,隔几个月或几年就有新的…

java+idea+mysql采用医疗AI自然语言处理技术的3D智能导诊导系统源码

javaideamysql采用医疗AI自然语言处理技术的3D智能导诊导系统源码 随着人工智能技术的快速发展,语音识别与自然语言理解技术的成熟应用,基于人工智能的智能导诊导医逐渐出现在患者的生活视角中,智能导诊系统应用到医院就医场景中&#xff0c…

jvm-接口调用排查

问题描述 线上碰到个问题,某个接口调用时间特别长,线上调用接口直接报gateway time out 分析处理 1、先关闭该功能 (该功能是非核心功能) 2、本地起服务连环境排查,发现本地正常。并且线上其他接口正常,…

机器学习笔记——浅析L2,1范数正则化的线性回归

前言 嘻嘻,刚开始搓逾期了快两周的线性回归实验报告,为了让报告稍微不那么平淡不得不啃论文。 本文从最基本的线性回归开始,对比不同正则化方法的特点和作用,推广到多任务问题并引出L2,1范数正则化,卑微小采购尝试去…

顺序表复习(C语言版)

数据结构是什么? 数据结构就是为了把数据管理起来,方便我们的增删查改 数据结构是计算机存储、组织数据的方式 数组就是一种最基础的数据结构 顺序表是什么? 顺序表就是数组 Int arr[100] {1,2,3,4,5,x,……} 修改某个数据&#xff1a…

【leetcode面试经典150题】56. 基本计算器(C++)

【leetcode面试经典150题】专栏系列将为准备暑期实习生以及秋招的同学们提高在面试时的经典面试算法题的思路和想法。本专栏将以一题多解和精简算法思路为主,题解使用C语言。(若有使用其他语言的同学也可了解题解思路,本质上语法内容一致&…

Mac下删除旧版本.net sdk

参照微软官网给的方法,Releases dotnet/cli-lab (github.com) 好像不能直接的解决问题,我做一下补充,希望对需要删除旧版本sdk的小伙伴们有所帮助 1:下载工具包 Releases dotnet/cli-lab (github.com) 2:打开终端,cd切换到该文件的制定目录 3:然后按照提示一步步执行…

mybatis使用

mybatis使用 一、添加配置文件 在application.properties配置文件文件中添加数据库连接信息 spring.datasource.driver-class-namecom.mysql.cj.jdbc.Driver spring.datasource.urljdbc:mysql://localhost:3306/your_database_name?useUnicodetrue&characterEncodingUTF-…

java核心类

一,String字符串 1.1,String字符串是引用类型,且不可变 String str1 "Hello";String str2 str1.concat(" World"); // 使用concat方法连接字符串,返回一个新的字符串对象System.out.println(str1); // 输出:Hello,原始…

C语言:复习

文章目录 思维导图数组和指针库函数的模拟实现判断大小端 最近知识学的差不多了,因此开始复习,本篇开始的是对于C语言的复习 思维导图 下面就依据下图,进行内容的整理 数组和指针 这个模块算是C语言中比较大的一个模块了,具体概…

IO——线程

1. 什么是线程 1.1概念 线程是一个轻量级的进程,为了提高系统的性能引入线程。 线程和进程都参与统一的调度。 在同一个进程中可以创建的多个线程, 共享进程资源。 (Linux里同样用task_struct来描述一个线程) 1.2进程和线程的区别 相同点…

【Vue】Vue中使一个div铺满全屏

在Vue中实现div全屏铺满的方式与纯CSS实现类似&#xff0c;只是在Vue组件中应用CSS的方式略有不同。 最近在项目开发中&#xff0c;就遇到了这个问题&#xff0c;特此记录一下&#xff0c;方便大伙避坑。 有这么一段代码&#xff1a; <template><div class"fu…

JS - 在JS中常用的运算符

学过编程语言的都知道一种大部分编程语言其实都存在许多相似的地方&#xff0c;比如数学中的四则运算&#xff0c;这个在JS中同样生效&#xff0c;不过在JS中&#xff0c;有进行部分拓展&#xff0c;这个也是其他语言中都有的&#xff0c;每个语言都有其功能和特性&#xff0c;…

流媒体协议--RTMP

文章目录 RTMP播放基本流程TCP握手过程RTMP握手过程connect连接createStream 创建流play 播放命令deleteStream删除流RTMP数据组成 RTMP(Real Time Messaging Protocol)是一个应用层协议&#xff0c;主要用于在Flash player和服务器之间传输视频、音频、控制命令等内容。 该协议…

类和对象-对象特性-类对象作为类成员

类对象作为类成员 #include<iostream> #include<string> using namespace std; class Phone{ public:Phone(string pName){m_pNamepName;}string m_pName; }; class Person{ public:Person(string name,string pName):m_Name(name),m_Phone(pName){}string m_Nam…

【笔试强训_Day06】

文章目录 1.字符串相乘 1.字符串相乘 题目链接 解题思路&#xff1a; 高精度乘法&#xff0c;注意要学会下面这种列式相乘的形式&#x1f34e; 注意细节❗&#xff1a; ① &#x1f34e; 首先把列式相乘的数据都存放到数组中去&#xff0c; 然后再对数组中的数据进行取余进…

C++:运算符重载和“const”成员

hello&#xff0c;各位小伙伴&#xff0c;本篇文章跟大家一起学习《C&#xff1a;运算符重载》&#xff0c;感谢大家对我上一篇的支持&#xff0c;如有什么问题&#xff0c;还请多多指教 &#xff01; 文章目录 赋值运算符重载1. 运算符重载2.赋值运算符重载第一个点第二个点&…