WSL-Ubuntu環境でPySide6のウィンドウを作成したら日本語が文字化けした。

python コンピュータ
python

タイトルバーが文字化けしていたので、日本語フォントを読み込むようにしてみました。

import sys
from PySide6.QtWidgets import QApplication,QMainWindow
from PySide6.QtGui import QFont
from PySide6.QtGui import QFont, QFontDatabase

# メインウィンドウ
class MyMainWindow(QMainWindow):

    # コンストラクタ
    def __init__(self):
        # スーパー(親)クラスのコンストラクタの呼び出し
        super().__init__()
        # WSL-Ubuntuでフォント設定
        if sys.platform == 'linux':
            font_path = "/usr/share/fonts/truetype//fonts-japanese-gothic.ttf"
            font_id = QFontDatabase.addApplicationFont(font_path)
            font_family = QFontDatabase.applicationFontFamilies(font_id)[0]
            font = QFont(font_family)
            self.setFont(font)
        # ウィンドウサイズの設定
        self.setGeometry(0, 0, 640, 400)
        # フォームのタイトルを設定
        self.setWindowTitle("QMainWindowのサンプル")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MyMainWindow()
    window.show()
    sys.exit(app.exec())

fontのパスを環境に合わせる必要がありそうです。

コメント