None:self.textEditor=ovid.textEditordefsetBoldT"/> None:self.textEditor=ovid.textEditordefsetBoldT">

Rumah  >  Artikel  >  pembangunan bahagian belakang  >  Gunakan PyQt6 untuk menukar format aksara

Gunakan PyQt6 untuk menukar format aksara

PHPz
PHPzke hadapan
2024-02-09 18:57:03634semak imbas

使用 PyQt6 切换字符格式

Kandungan soalan

Saya sedang menulis pemproses perkataan tersuai sebagai projek hobi. Saya menggunakan python dan pyqt6.

Saya menulis perkara berikut. Tujuannya ialah jika saya memilih beberapa teks dan menggunakan pemformatan tebal (cth. dengan menekan "ctrl-b") ia akan menukar pemformatan. Khususnya, jika semua teks yang dipilih adalah tebal, pemformatan tebal harus dialih keluar. Jika tidak, ia akan menggunakan pemformatan tebal.

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)

Walau bagaimanapun, ia tidak mengalih keluar pemformatan tebal.

Sebagai contoh, dalam ayat "ini adalah ujian", jika saya memilih "adalah" dan menggunakan pemformatan tebal, saya mendapat "ini is a ujian" di mana "ialah a" adalah sesuai dengan huruf tebal Namun, memilih Sekali masuk tempat, jika saya menekan "ctrl-b", ia masih kekal tebal Jika saya menyahpilih aksara pertama atau terakhir, togol tebal berfungsi seperti yang diharapkan (saya telah cuba menyongsangkan logik if/else, tetapi itu tidak berfungsi. juga gagal)

Apa yang saya terlepas?

Kemas kini: Saya telah menambah kes ujian minimum yang berfungsi di https://gist.github.com/ovid/65936985c6838c0220620cf40ba935fa


Jawapan yang betul


setboldtext 函数的问题在于它使用 self.texteditor.currentcharformat().fontweight(), ini hanya menunjukkan huruf tebal pada status kedudukan kursor semasa , dan bukannya memformat keseluruhan teks yang dipilih. Jika kursor anda berada di permulaan atau penghujung pemilihan, ia mungkin tidak mewakili pemformatan keseluruhan pilihan dengan tepat.

Jadi saya menggunakan kursor sedia ada dan melaraskannya mengikut keperluan untuk menyemak pemformatan dan menggunakan berat fon baharu secara terus pada setfontweight().

Sekarang ia kelihatan seperti ini:

Kod dikemas kini:

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()

Atas ialah kandungan terperinci Gunakan PyQt6 untuk menukar format aksara. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Artikel ini dikembalikan pada:stackoverflow.com. Jika ada pelanggaran, sila hubungi admin@php.cn Padam