LoginSignup
0
0

More than 5 years have passed since last update.

Qtを使ってmacOS上で等幅フォントで日本語を描画する

Last updated at Posted at 2018-11-10

この記事は、私がstackoverflowで質問した結果から書き起こしたものです。
https://ja.stackoverflow.com/questions/41083/

macOSでC++とQtを使って、等幅フォントでテキストを描画するとき、半角2文字と全角1文字の幅が一致するように描画したいと思いましたが、単純にやっただけだと、幅が変わってしまいました。

void MainWindow::paintEvent(QPaintEvent *event)
{
    QPainter p(this);
    p.setFont(QFont("Monaco", 20));
    p.drawText(0, 30, "WWWWWWWWWW");
    p.drawText(0, 60, "||||||||||");
    p.drawText(0, 90, "あああああ");
}

image.png

Monacoは等幅フォントですが、欧文フォントなので、漢字1文字の幅と英数2文字の幅が一致しません。

日欧混合で等幅描画したいとき、ひと工夫が必要です。

void MainWindow::paintEvent(QPaintEvent *event)
{
    QPainter p(this);
    QFont font = QFontDatabase().font("Osaka", "Regular-Mono", 20);
    p.setFont(font);
    p.drawText(0, 30, "WWWWWWWWWW");
    p.drawText(0, 60, "||||||||||");
    p.drawText(0, 90, "あああああ");
}

image.png

Osakaは確実に日本語フォントです。ただ、Osakaフォントをそのまま使うとプロポーショナルになってしまうため、明示的に等幅フォントを取得する必要があります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0