August 28, 2024
PyQt is a powerful framework that allows developers to create sophisticated graphical user interfaces (GUIs) in Python. In this tutorial, you'll learn how to build a simple text editor using PyQt6 that includes features for changing the font family, size, and applying text styles like bold, italic, and underline.
To begin, ensure PyQt6 is installed in your Python environment:
pip install PyQt6
Here’s how to create a text editor with advanced text formatting options.
Start by importing the necessary modules:
from PyQt6.QtWidgets import QApplication, QMainWindow, QTextEdit, QAction, QToolBar, QFontComboBox, QSpinBox
from PyQt6.QtGui import QFont, QIcon
from PyQt6.QtCore import Qt
Define your main window class, inheriting from QMainWindow
:
class TextEditor(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.textEdit = QTextEdit(self)
self.setCentralWidget(self.textEdit)
self.setWindowTitle('Simple Text Editor - PyQt6')
self.setGeometry(300, 300, 600, 400)
self.createToolbar()
def createToolbar(self):
toolbar = QToolBar("Toolbar", self)
self.addToolBar(toolbar)
fontBox = QFontComboBox(toolbar)
fontBox.currentFontChanged.connect(self.fontFamilyChanged)
toolbar.addWidget(fontBox)
fontSizeBox = QSpinBox(toolbar)
fontSizeBox.setValue(14)
fontSizeBox.valueChanged.connect(self.fontSizeChanged)
toolbar.addWidget(fontSizeBox)
boldAction = QAction(QIcon('icons/bold.png'), 'Bold', self)
boldAction.triggered.connect(self.boldText)
toolbar.addAction(boldAction)
italicAction = QAction(QIcon('icons/italic.png'), 'Italic', self)
italicAction.triggered.connect(self.italicText)
toolbar.addAction(italicAction)
underlineAction = QAction(QIcon('icons/underline.png'), 'Underline', self)
underlineAction.triggered.connect(self.underlineText)
toolbar.addAction(underlineAction)
def fontFamilyChanged(self, font):
self.textEdit.setCurrentFont(font)
def fontSizeChanged(self, size):
self.textEdit.setFontPointSize(size)
def boldText(self):
currentWeight = self.textEdit.fontWeight()
if currentWeight == QFont.Weight.Bold:
self.textEdit.setFontWeight(QFont.Weight.Normal)
else:
self.textEdit.setFontWeight(QFont.Weight.Bold)
def italicText(self):
currentState = self.textEdit.fontItalic()
self.textEdit.setFontItalic(not currentState)
def underlineText(self):
currentState = self.textEdit.fontUnderline()
self.textEdit.setFontUnderline(not currentState)
To run the application, add the following code:
if __name__ == '__main__':
app = QApplication([])
editor = TextEditor()
editor.show()
app.exec()
This tutorial has guided you through building a simple text editor with PyQt6. You've learned how to add text formatting features such as changing fonts and applying styles. These fundamental skills are a great starting point for expanding into more detailed PyQt projects.
@2024 Easely, Inc. All rights reserved.