欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python3+PyQt5 實(shí)現(xiàn)Rich文本的行編輯方法

 更新時(shí)間:2019年06月17日 11:45:21   作者:basisworker  
今天小編就為大家分享一篇python3+PyQt5 實(shí)現(xiàn)Rich文本的行編輯方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧

本文通過Python3+PyQt5實(shí)現(xiàn)《python Qt Gui 快速編程》這本書13章程序Rich文本的行編輯,可以通過鼠標(biāo)右鍵選擇對文本進(jìn)行加粗,斜體,下劃線,刪除線,上標(biāo),下標(biāo)等編輯。

#!/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 實(shí)現(xiàn)Rich文本的行編輯方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 詳解重置Django migration的常見方式

    詳解重置Django migration的常見方式

    這篇文章主要介紹了詳解重置Django migration的常見方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-02-02
  • Python爬蟲Xpath定位數(shù)據(jù)的兩種方法

    Python爬蟲Xpath定位數(shù)據(jù)的兩種方法

    這篇文章主要介紹了Python爬蟲Xpath定位數(shù)據(jù)的方法,第一種方法直接右鍵,將文章路徑復(fù)制下來點(diǎn)擊Copy?full?Xpath,方法二使用@制定標(biāo)簽屬性,搜索指定位置,每種方法給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2022-07-07
  • OpenCV-Python實(shí)現(xiàn)多模板匹配

    OpenCV-Python實(shí)現(xiàn)多模板匹配

    模板匹配就是在一幅圖像中尋找另一幅模板圖像最匹配,本文主要實(shí)現(xiàn)了多模板匹配,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-06-06
  • 詳解Python是如何處理不同時(shí)區(qū)的

    詳解Python是如何處理不同時(shí)區(qū)的

    時(shí)區(qū)是指在地球上不同地方的時(shí)間差異,地球分為?24?個(gè)時(shí)區(qū),每個(gè)時(shí)區(qū)都相對于格林威治標(biāo)準(zhǔn)時(shí)間或協(xié)調(diào)世界時(shí)(UTC)有所偏移。本文主要和大家來聊聊Python是如何處理不同時(shí)區(qū)的,希望對大家有所幫助
    2023-02-02
  • python sys,os,time模塊的使用(包括時(shí)間格式的各種轉(zhuǎn)換)

    python sys,os,time模塊的使用(包括時(shí)間格式的各種轉(zhuǎn)換)

    這篇文章主要介紹了python sys,os,time模塊的使用(包括時(shí)間格式的各種轉(zhuǎn)換),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-04-04
  • python3 中的幾種除法介紹,小數(shù)的不同顯示

    python3 中的幾種除法介紹,小數(shù)的不同顯示

    這篇文章主要介紹了python3 中的幾種除法介紹,小數(shù)的不同顯示,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-03-03
  • Python+Selenium實(shí)現(xiàn)瀏覽器標(biāo)簽頁的切換

    Python+Selenium實(shí)現(xiàn)瀏覽器標(biāo)簽頁的切換

    在實(shí)際工作中,我們經(jīng)常會(huì)遇到頁面切換的情況。就比如當(dāng)點(diǎn)擊了某個(gè)功能的按鈕后,瀏覽器出現(xiàn)了新的標(biāo)簽頁,需要在這些標(biāo)簽頁之間進(jìn)行切換。本文將利用Selenium實(shí)現(xiàn)這一功能,需要的可以參考一下
    2022-06-06
  • python實(shí)現(xiàn)的DES加密算法和3DES加密算法實(shí)例

    python實(shí)現(xiàn)的DES加密算法和3DES加密算法實(shí)例

    這篇文章主要介紹了python實(shí)現(xiàn)的DES加密算法和3DES加密算法,以實(shí)例形式較為詳細(xì)的分析了DES加密算法和3DES加密算法的原理與實(shí)現(xiàn)技巧,需要的朋友可以參考下
    2015-06-06
  • Python中的簡寫操作(for、if簡寫、匿名函數(shù))

    Python中的簡寫操作(for、if簡寫、匿名函數(shù))

    這篇文章主要介紹了Python中的簡寫操作(for、if簡寫、匿名函數(shù)),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • Python sublime安裝及配置過程詳解

    Python sublime安裝及配置過程詳解

    這篇文章主要介紹了Python sublime安裝及配置過程詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-06-06

最新評論