Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Qt for Python
  4. how do you bold and un-bold a selected text? [pyqt or pyside]
Forum Updated to NodeBB v4.3 + New Features

how do you bold and un-bold a selected text? [pyqt or pyside]

Scheduled Pinned Locked Moved Solved Qt for Python
5 Posts 2 Posters 6.1k Views 2 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • adfinem_risingA Offline
    adfinem_risingA Offline
    adfinem_rising
    wrote on last edited by adfinem_rising
    #1

    this code bolds the whole line were the cursor is placed.
    how would it be possible to only bold a text that i selected?

    import sys
    from PyQt5 import QtWidgets
    from PyQt5.QtWidgets import *
    from PyQt5.QtGui import *
    from PyQt5.QtCore import *
    from PyQt5.uic import loadUiType
    import sip
    
    
    
    class Widget(QWidget):
        def __init__(self):
            super().__init__()
            self.setGeometry(500, 500, 700, 700)
            self.te = QTextEdit(self)
            self.te.setText('hello, this is big problem. why no bold one word?')
    
            self.button = QPushButton("bold the text", self)
            self.button.move(150, 200)
            self.button.clicked.connect(self.bold_text)
    
            self.document = self.te.document()
            self.cursor = QTextCursor(self.document)
    
        def bold_text(self):
            # bold the text
            
            self.cursor.movePosition(QTextCursor.Start)
            self.cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor)
            self.format = QTextCharFormat()
            self.format.setFontWeight(QFont.Bold)
            self.cursor.mergeCharFormat(self.format)
    
    if __name__ == "__main__":
    
        app = QApplication(sys.argv)
        w = Widget()
        w.show()
        sys.exit(app.exec_())
    
    1 Reply Last reply
    0
    • adfinem_risingA Offline
      adfinem_risingA Offline
      adfinem_rising
      wrote on last edited by adfinem_rising
      #2

      greetings friends, i have not found the exact solution that i wanted, but i found a solution that is even greater than what my peasant brain can comprehend..

      i have found an example in the qt for python documentation and dumbed it down. i even threw in the italic and underline in case someone needs it

      enjoy <3

      import sys
      from PyQt5 import QtWidgets as qtw
      from PyQt5 import QtCore as qtc
      from PyQt5 import QtGui as qtg 
      
      #import resources # create a qrc file for your images my guy ;) alan d moore taught me that
      
      # learned from a programming pyqt god, 
      # none other than this guy: https://www.youtube.com/watch?v=QdOoZ7edqXc&list=PLXlKT56RD3kBu2Wk6ajCTyBMkPIGx7O37&index=4
      
      
      class MainWindow(qtw.QMainWindow):
          def __init__(self):
              super().__init__()
              # ===========================
              # code starts here
              # ===========================
              # text edit
              self.textedit = qtw.QTextEdit()
              self.setCentralWidget(self.textedit)
              
              # call toolbar method
              self.create_toolbar()
      
              # ===========================
              # code ends here
              # ===========================
              self.show()
      
          def create_toolbar(self):
              # font weight toolbar
              font_weight_toolbar = self.addToolBar("Font Weight") #QToolBar
              font_weight_toolbar.setIconSize(qtc.QSize(18,18))
      
              # qt documentation for python: https://doc.qt.io/qtforpython/
              # example code from documentation:  https://doc.qt.io/qtforpython/examples/example_widgets_richtext_textedit.html
              
              # complicated code for bold
              self._action_text_bold = font_weight_toolbar.addAction(qtg.QIcon(':/images/bold.png'), "&Bold", self.bold_text)
              self._action_text_bold.setShortcut(qtc.Qt.CTRL | qtc.Qt.Key_B)
              bold_font = qtg.QFont()
              bold_font.setBold(True)
              self._action_text_bold.setFont(bold_font)
              self._action_text_bold.setCheckable(True)
              self._action_text_bold.setStatusTip("Toggle whether the font weight is bold or not")
      
              # complicated code for italic
              self._action_text_italic = font_weight_toolbar.addAction(qtg.QIcon(':/images/italic.png'), "&Italic", self.italic_text)
              self._action_text_italic.setShortcut(qtc.Qt.CTRL | qtc.Qt.Key_I)
              italic_font = qtg.QFont()
              italic_font.setItalic(True)
              self._action_text_italic.setFont(italic_font)
              self._action_text_italic.setCheckable(True)
              self._action_text_italic.setStatusTip("Toggle whether the font is italic or not")
      
              # complicated code for underline
              self._action_text_underline = font_weight_toolbar.addAction(qtg.QIcon(':/images/underline.png'), "&Underline", self.underlined_text)
              self._action_text_underline.setShortcut(qtc.Qt.CTRL | qtc.Qt.Key_U)
              underlined_font = qtg.QFont()
              underlined_font.setUnderline(True)
              self._action_text_underline.setFont(underlined_font)
              self._action_text_underline.setCheckable(True)
              self._action_text_underline.setStatusTip("Toggle whether the font is underlined or not")
      
          def bold_text(self): 
              fmt = qtg.QTextCharFormat()
              weight = qtg.QFont.DemiBold if self._action_text_bold.isChecked() else qtg.QFont.Normal
              fmt.setFontWeight(weight)
              self.merge_format_on_word_or_selection(fmt)
      
          def italic_text(self):
              fmt = qtg.QTextCharFormat()
              fmt.setFontItalic(self._action_text_italic.isChecked())
              self.merge_format_on_word_or_selection(fmt)
      
          def underlined_text(self):
              fmt = qtg.QTextCharFormat()
              fmt.setFontUnderline(self._action_text_underline.isChecked())
              self.merge_format_on_word_or_selection(fmt)
      
          def merge_format_on_word_or_selection(self, format):
              cursor = self.textedit.textCursor()
              if not cursor.hasSelection(): 
                  cursor.select(qtg.QTextCursor.WordUnderCursor)
              cursor.mergeCharFormat(format)
              self.textedit.mergeCurrentCharFormat(format)
      
      
      if __name__ == "__main__":
          app = qtw.QApplication.instance()
          if app is None:            
              # in every pyqt application it is required to create the object of QApplication
              app = qtw.QApplication(sys.argv)
          else:
              print('QApplication instance already exists: %s' % str(app))
      
      
          # initialize and show Qwidget object
          main = MainWindow()
          # main window properties
          main.setWindowTitle("Text Editor")
          main.resize(650,500)
          main.setMinimumSize(550,450)
          main.setWindowIcon(qtg.QIcon(":/images/notepad.png"))
          
          try:
              sys.exit(app.exec_())
          except SystemExit:
              print("Closing Window...")
      
      1 Reply Last reply
      1
      • SGaistS Offline
        SGaistS Offline
        SGaist
        Lifetime Qt Champion
        wrote on last edited by
        #3

        Hi,

        Can you link the example you used ? It might also help others coming in your topic.

        Interested in AI ? www.idiap.ch
        Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

        1 Reply Last reply
        0
        • adfinem_risingA Offline
          adfinem_risingA Offline
          adfinem_rising
          wrote on last edited by adfinem_rising
          #4

          with pleasure my guy! here it is:

          example code from documentation (bold, italic, underline):
          https://doc.qt.io/qtforpython/examples/example_widgets_richtext_textedit.html

          qt documentation for python:
          https://doc.qt.io/qtforpython/

          1 Reply Last reply
          0
          • SGaistS Offline
            SGaistS Offline
            SGaist
            Lifetime Qt Champion
            wrote on last edited by
            #5

            Thanks !

            Interested in AI ? www.idiap.ch
            Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

            1 Reply Last reply
            0

            • Login

            • Login or register to search.
            • First post
              Last post
            0
            • Categories
            • Recent
            • Tags
            • Popular
            • Users
            • Groups
            • Search
            • Get Qt Extensions
            • Unsolved