Heim  >  Artikel  >  Backend-Entwicklung  >  Verwenden Sie PyQt6, um Zeichenformate zu wechseln

Verwenden Sie PyQt6, um Zeichenformate zu wechseln

PHPz
PHPznach vorne
2024-02-09 18:57:03631Durchsuche

使用 PyQt6 切换字符格式

Frageninhalt

Ich schreibe als Hobbyprojekt ein benutzerdefiniertes Textverarbeitungsprogramm. Ich verwende Python und pyqt6.

Ich habe Folgendes geschrieben. Der Zweck besteht darin, dass die Formatierung geändert wird, wenn ich Text auswähle und eine fette Formatierung anwende (z. B. durch Drücken von „Strg-B“). Insbesondere wenn der gesamte ausgewählte Text fett ist, sollte die Fettformatierung entfernt werden. Andernfalls wird die Fettformatierung angewendet.

class OvidFont:
    def __init__(self, ovid) -> None:
        self.textEditor = ovid.textEditor

    def setBoldText(self) -> None:
        fmt = QTextCharFormat()
        if self.textEditor.currentCharFormat().fontWeight() != QFont.Weight.Bold:
            print("    setting bold")   # for debugging
            fmt.setFontWeight(QFont.Weight.Bold)
        else:
            print("    setting normal") # for debugging
            fmt.setFontWeight(QFont.Weight.Normal)
        self.textEditor.textCursor().mergeCharFormat(fmt)

Die Fettformatierung wird jedoch nicht entfernt.

Wenn ich beispielsweise im Satz „Dies ist ein Test“ „ist ein“ auswähle und Fettformatierung anwende, erhalte ich „Dies ist ein Test“, wobei „Ist ein“ entsprechend fett gedruckt ist Wenn ich „Strg-B“ drücke, bleibt es immer noch fett. Wenn ich das erste oder letzte Zeichen abwähle, funktioniert die Fett-Umschaltung wie erwartet (ich habe versucht, die if/else-Logik umzukehren, aber das funktioniert nicht. auch fehlgeschlagen) Was habe ich verpasst?

Update: Ich habe unter https://gist.github.com/ovid/65936985c6838c0220620cf40ba935fa einen funktionierenden minimalen Testfall hinzugefügt aktuelle Cursorposition, anstatt den gesamten ausgewählten Text zu formatieren. Wenn sich Ihr Cursor am Anfang oder Ende der Auswahl befindet, stellt er möglicherweise nicht die Formatierung der gesamten Auswahl dar.

Also habe ich den vorhandenen Cursor verwendet und ihn nach Bedarf angepasst, um die Formatierung zu überprüfen und die neue Schriftstärke direkt auf das

anzuwenden.

Jetzt sieht es so aus:


Aktualisierter Code: setboldtext 函数的问题在于它使用 self.texteditor.currentcharformat().fontweight()

import sys
from PyQt6.QtWidgets import QTextEdit, QToolButton, QApplication, QMainWindow, QToolBar
from PyQt6.QtGui import QFont, QShortcut, QKeySequence, QTextCharFormat, QTextCursor

class OvidFont:
    def __init__(self, ovid) -> None:
        self.textEditor = ovid.textEditor

    def setBoldText(self):
        cursor = self.textEditor.textCursor()

        # If there's a selection, and the cursor is not at the block start and at the beginning of the selection,
        # move the cursor to the end of the selection
        if cursor.hasSelection() and not cursor.atBlockStart() and cursor.position() == cursor.selectionStart():
            cursor.setPosition(cursor.selectionEnd())

        # Check if the text (either selected or where the cursor is) is bold
        is_bold = cursor.charFormat().fontWeight() == QFont.Weight.Bold

        # Apply the new weight based on the current state
        new_weight = QFont.Weight.Normal if is_bold else QFont.Weight.Bold
        self.textEditor.setFontWeight(new_weight)

        print(f"Bold set to: {'Normal' if is_bold else 'Bold'}")

class Ovid(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("Ovid")
        self.setGeometry(100, 100, 200, 200)
        self.textEditor = QTextEdit()
        self.setCentralWidget(self.textEditor)
        self.fonts = OvidFont(self)

        self.toolbar = QToolBar("Main Toolbar")
        self.addToolBar(self.toolbar)

        bold_button = QToolButton()
        bold_button.setText("B")
        bold_button.setFont(QFont("Arial", 16, QFont.Weight.Bold))
        bold_button.setToolTip("Bold")
        bold_button.clicked.connect(self.fonts.setBoldText)
        self.toolbar.addWidget(bold_button)

        QShortcut(QKeySequence("Ctrl+B"), self, self.fonts.setBoldText)

def main():
    app = QApplication(sys.argv)
    ex = Ovid()
    ex.show()
    sys.exit(app.exec())

if __name__ == "__main__":
    main()

Das obige ist der detaillierte Inhalt vonVerwenden Sie PyQt6, um Zeichenformate zu wechseln. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Dieser Artikel ist reproduziert unter:stackoverflow.com. Bei Verstößen wenden Sie sich bitte an admin@php.cn löschen