python3+PyQt5 实现Rich文本的行编辑方法


Posted in Python onJune 17, 2019

本文通过Python3+PyQt5实现《python Qt Gui 快速编程》这本书13章程序Rich文本的行编辑,可以通过鼠标右键选择对文本进行加粗,斜体,下划线,删除线,上标,下标等编辑。

#!/usr/bin/env python3

import platform
import sys
import html
from PyQt5.QtCore import QSize, Qt,pyqtSignal
from PyQt5.QtGui import QColor, QFont,QFontMetrics, QIcon, QKeySequence, QPixmap,QTextCharFormat
from PyQt5.QtWidgets import QAction,QApplication,QMenu,QTextEdit



class RichTextLineEdit(QTextEdit):
  returnPressed=pyqtSignal()
  (Bold, Italic, Underline, StrikeOut, Monospaced, Sans, Serif,
   NoSuperOrSubscript, Subscript, Superscript) = range(10)


  def __init__(self, parent=None):
    super(RichTextLineEdit, self).__init__(parent)

    self.monofamily = "courier"
    self.sansfamily = "helvetica"
    self.seriffamily = "times"
    self.setLineWrapMode(QTextEdit.NoWrap)
    self.setTabChangesFocus(True)
    self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
    self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
    fm = QFontMetrics(self.font())
    h = int(fm.height() * (1.4 if platform.system() == "Windows"
                  else 1.2))
    self.setMinimumHeight(h)
    self.setMaximumHeight(int(h * 1.2))
    self.setToolTip("Press <b>Ctrl+M</b> for the text effects "
        "menu and <b>Ctrl+K</b> for the color menu")


  def toggleItalic(self):
    self.setFontItalic(not self.fontItalic())


  def toggleUnderline(self):
    self.setFontUnderline(not self.fontUnderline())


  def toggleBold(self):
    self.setFontWeight(QFont.Normal
        if self.fontWeight() > QFont.Normal else QFont.Bold)


  def sizeHint(self):
    return QSize(self.document().idealWidth() + 5,
           self.maximumHeight())


  def minimumSizeHint(self):
    fm = QFontMetrics(self.font())
    return QSize(fm.width("WWWW"), self.minimumHeight())


  def contextMenuEvent(self, event):
    self.textEffectMenu()


  def keyPressEvent(self, event):
    if event.modifiers() & Qt.ControlModifier:
      handled = False
      if event.key() == Qt.Key_B:
        self.toggleBold()
        handled = True
      elif event.key() == Qt.Key_I:
        self.toggleItalic()
        handled = True
      elif event.key() == Qt.Key_K:
        self.colorMenu()
        handled = True
      elif event.key() == Qt.Key_M:
        self.textEffectMenu()
        handled = True
      elif event.key() == Qt.Key_U:
        self.toggleUnderline()
        handled = True
      if handled:
        event.accept()
        return
    if event.key() in (Qt.Key_Enter, Qt.Key_Return):
      self.returnPressed.emit()
      event.accept()
    else:
      QTextEdit.keyPressEvent(self, event)


  def colorMenu(self):
    pixmap = QPixmap(22, 22)
    menu = QMenu("Colour")
    for text, color in (
        ("&Black", Qt.black),
        ("B&lue", Qt.blue),
        ("Dark Bl&ue", Qt.darkBlue),
        ("&Cyan", Qt.cyan),
        ("Dar&k Cyan", Qt.darkCyan),
        ("&Green", Qt.green),
        ("Dark Gr&een", Qt.darkGreen),
        ("M&agenta", Qt.magenta),
        ("Dark Mage&nta", Qt.darkMagenta),
        ("&Red", Qt.red),
        ("&Dark Red", Qt.darkRed)):
      color = QColor(color)
      pixmap.fill(color)
      action = menu.addAction(QIcon(pixmap), text, self.setColor)
      action.setData(color)
    self.ensureCursorVisible()
    menu.exec_(self.viewport().mapToGlobal(
          self.cursorRect().center()))


  def setColor(self):
    action = self.sender()
    if action is not None and isinstance(action, QAction):
      color = QColor(action.data())
      if color.isValid():
        self.setTextColor(color)


  def textEffectMenu(self):
    format = self.currentCharFormat()
    menu = QMenu("Text Effect")
    for text, shortcut, data, checked in (
        ("&Bold", "Ctrl+B", RichTextLineEdit.Bold,
         self.fontWeight() > QFont.Normal),
        ("&Italic", "Ctrl+I", RichTextLineEdit.Italic,
         self.fontItalic()),
        ("Strike &out", None, RichTextLineEdit.StrikeOut,
         format.fontStrikeOut()),
        ("&Underline", "Ctrl+U", RichTextLineEdit.Underline,
         self.fontUnderline()),
        ("&Monospaced", None, RichTextLineEdit.Monospaced,
         format.fontFamily() == self.monofamily),
        ("&Serifed", None, RichTextLineEdit.Serif,
         format.fontFamily() == self.seriffamily),
        ("S&ans Serif", None, RichTextLineEdit.Sans,
         format.fontFamily() == self.sansfamily),
        ("&No super or subscript", None,
         RichTextLineEdit.NoSuperOrSubscript,
         format.verticalAlignment() ==
         QTextCharFormat.AlignNormal),
        ("Su&perscript", None, RichTextLineEdit.Superscript,
         format.verticalAlignment() ==
         QTextCharFormat.AlignSuperScript),
        ("Subs&cript", None, RichTextLineEdit.Subscript,
         format.verticalAlignment() ==
         QTextCharFormat.AlignSubScript)):
      action = menu.addAction(text, self.setTextEffect)
      if shortcut is not None:
        action.setShortcut(QKeySequence(shortcut))
      action.setData(data)
      action.setCheckable(True)
      action.setChecked(checked)
    self.ensureCursorVisible()
    menu.exec_(self.viewport().mapToGlobal(
          self.cursorRect().center()))


  def setTextEffect(self):
    action = self.sender()
    if action is not None and isinstance(action, QAction):
      what = action.data()
      if what == RichTextLineEdit.Bold:
        self.toggleBold()
        return
      if what == RichTextLineEdit.Italic:
        self.toggleItalic()
        return
      if what == RichTextLineEdit.Underline:
        self.toggleUnderline()
        return
      format = self.currentCharFormat()
      if what == RichTextLineEdit.Monospaced:
        format.setFontFamily(self.monofamily)
      elif what == RichTextLineEdit.Serif:
        format.setFontFamily(self.seriffamily)
      elif what == RichTextLineEdit.Sans:
        format.setFontFamily(self.sansfamily)
      if what == RichTextLineEdit.StrikeOut:
        format.setFontStrikeOut(not format.fontStrikeOut())
      if what == RichTextLineEdit.NoSuperOrSubscript:
        format.setVerticalAlignment(
            QTextCharFormat.AlignNormal)
      elif what == RichTextLineEdit.Superscript:
        format.setVerticalAlignment(
            QTextCharFormat.AlignSuperScript)
      elif what == RichTextLineEdit.Subscript:
        format.setVerticalAlignment(
            QTextCharFormat.AlignSubScript)
      self.mergeCurrentCharFormat(format)


  def toSimpleHtml(self):
    htmltext = ""
    black = QColor(Qt.black)
    block = self.document().begin()
    while block.isValid():
      iterator = block.begin()
      while iterator != block.end():
        fragment = iterator.fragment()
        if fragment.isValid():
          format = fragment.charFormat()
          family = format.fontFamily()
          color = format.foreground().color()         
          text=html.escape(fragment.text())
          if (format.verticalAlignment() ==
            QTextCharFormat.AlignSubScript):
            text = "<sub>{0}</sub>".format(text)
          elif (format.verticalAlignment() ==
             QTextCharFormat.AlignSuperScript):
            text = "<sup>{0}</sup>".format(text)
          if format.fontUnderline():
            text = "<u>{0}</u>".format(text)
          if format.fontItalic():
            text = "<i>{0}</i>".format(text)
          if format.fontWeight() > QFont.Normal:
            text = "<b>{0}</b>".format(text)
          if format.fontStrikeOut():
            text = "<s>{0}</s>".format(text)
          if color != black or family:
            attribs = ""
            if color != black:
              attribs += ' color="{0}"'.format(color.name())
            if family:
              attribs += ' face="{0}"'.format(family)
            text = "<font{0}>{1}</font>".format(attribs,text)
          htmltext += text
        iterator += 1
      block = block.next()
    return htmltext

if __name__ == "__main__":
  def printout(lineedit):
    print(str(lineedit.toHtml()))
    print(str(lineedit.toPlainText()))
    print(str(lineedit.toSimpleHtml()))        
  app = QApplication(sys.argv)
  lineedit = RichTextLineEdit()
  lineedit.returnPressed.connect(lambda:printout(lineedit))
  lineedit.show()
  lineedit.setWindowTitle("RichTextEdit")
  app.exec_()

以上这篇python3+PyQt5 实现Rich文本的行编辑方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Flask SQLAlchemy一对一,一对多的使用方法实践
Feb 10 Python
pycharm 使用心得(六)进行简单的数据库管理
Jun 06 Python
Python中json格式数据的编码与解码方法详解
Jul 01 Python
浅析python中的分片与截断序列
Aug 09 Python
python中快速进行多个字符替换的方法小结
Dec 15 Python
python爬取亚马逊书籍信息代码分享
Dec 09 Python
2019 Python最新面试题及答案16道题
Apr 11 Python
python利用selenium进行浏览器爬虫
Apr 25 Python
如何在python开发工具PyCharm中搭建QtPy环境(教程详解)
Feb 04 Python
python加密解密库cryptography使用openSSL生成的密匙加密解密
Feb 11 Python
解决jupyter notebook 前面书写后面内容消失的问题
Apr 13 Python
详解Python函数print用法
Jun 18 Python
Appium+python自动化之连接模拟器并启动淘宝APP(超详解)
Jun 17 #Python
python3+PyQt5 数据库编程--增删改实例
Jun 17 #Python
python3+PyQt5 创建多线程网络应用-TCP客户端和TCP服务器实例
Jun 17 #Python
python 应用之Pycharm 新建模板默认添加编码格式-作者-时间等信息【推荐】
Jun 17 #Python
python3+PyQt5 使用三种不同的简便项窗口部件显示数据的方法
Jun 17 #Python
对PyQt5中树结构的实现方法详解
Jun 17 #Python
PyQT实现菜单中的复制,全选和清空的功能的方法
Jun 17 #Python
You might like
php快速url重写更新版[需php 5.30以上]
2010/04/25 PHP
PHP+ajax实现获取新闻数据简单示例
2018/05/08 PHP
转义字符(\)对JavaScript中JSON.parse的影响概述
2013/07/17 Javascript
jQuery插件datepicker 日期连续选择
2015/06/12 Javascript
关于JS 预解释的相关理解
2016/06/28 Javascript
axios基本入门用法教程
2017/03/25 Javascript
使用Vue-Router 2实现路由功能实例详解
2017/11/14 Javascript
搭建element-ui的Vue前端工程操作实例
2018/02/23 Javascript
vue操作下拉选择器获取选择的数据的id方法
2018/08/24 Javascript
vue src动态加载请求获取图片的方法
2018/10/17 Javascript
使用微信小程序开发弹出框应用实例详解
2018/10/18 Javascript
js array数组对象操作方法汇总
2019/03/18 Javascript
在vue中获取微信支付code及code被占用问题的解决方法
2019/04/16 Javascript
JS定义函数的几种常用方法小结
2019/05/23 Javascript
小程序input数据双向绑定实现方法
2019/10/17 Javascript
Python实现给qq邮箱发送邮件的方法
2015/05/28 Python
Python实现建立SSH连接的方法
2015/06/03 Python
Python实现查找匹配项作处理后再替换回去的方法
2017/06/10 Python
利用python求相邻数的方法示例
2017/08/18 Python
python实现批量修改文件名代码
2017/09/10 Python
深入理解Python中的*重复运算符
2017/10/28 Python
关于探究python中sys.argv时遇到的问题详解
2021/02/23 Python
CSS3教程:边框属性border的极致应用
2009/04/02 HTML / CSS
自定义html标记替换html5新增元素
2008/10/17 HTML / CSS
西班牙汉普顿小姐:购买帆布鞋和太阳镜
2016/10/23 全球购物
德国净水壶和滤芯品牌:波尔德PearlCo(家用净水器)
2020/04/29 全球购物
十佳青年个人事迹材料
2014/01/28 职场文书
国庆促销活动总结
2014/08/29 职场文书
要账委托书范本
2014/09/15 职场文书
骨干教师个人总结
2015/02/11 职场文书
安全知识竞赛主持词
2015/06/30 职场文书
大学同学聚会感言
2015/07/30 职场文书
蔬果开业典礼发言稿应该怎么写?
2019/09/03 职场文书
python3 hdf5文件 遍历代码
2021/05/19 Python
Go遍历struct,map,slice的实现
2021/06/13 Golang
索尼ICF-36收音机评测
2022/04/30 无线电