Raspberry PiでのQt5日本語表示
やっと、RaspberryPi上で日本語表示を倒せたorz次回の名古屋Qt勉強会ネタに!(長via.me/-by6s2da #qtjp
— sazusさん (@sazus) 2013年5月7日
リツイート等もして頂いたので、blogに書いておく。
はじめに
Raspbianを日本語にがんばってローカライズしたとしても、
Qt5で日本語表示した場合に、日本語の文字列が豆腐にすらならず
非常に残念極まりない表示になります。
Widgetの場合
(対応前)
(対応後)
QMLの場合
(対応前)
(対応後)
動作確認 環境
- Raspberry Pi導入OS
- Raspbian "wheezy(Hard-float)”2013-02-09-wheezy-raspbian
- Qt5 :
- gitのtag v5.0.2
- configureにて、-prefix /usr/local/qt5piと設定してbuild
対応方法
- Qt5のlib以下の/fontディレクトリに日本語のフォントを入れる。
- Code上にて、導入した日本語フォントのfontfamilyをセットする。
ことにより対応可能です。
Qt5のlib以下の/fontディレクトリに日本語のフォントを入れる
私の環境では、"-prefix /usr/local/qt5pi"としているので、
/usr/local/qt5pi/lib/fonts/
に日本語フォントを入れちゃえばOKです。
導入先は、各自で環境設定を読み替えてください。
- 日本語フォントの取得
とりあえず、今回はtakao fontあたりを取得してみました。
$ sudo apt-get install fonts-takao
これで、Raspbianに
fonts-takao-gothic fonts-takao-mincho
が
/usr/share/fonts/truetype/takao-gothic/
/usr/share/fonts/truetype/takao-mincho/
以下に導入されます。
- 日本語フォントをQt5のフォントディレクトリーにコピーする
先ほどのフォント(今回は、takao-gothicの方)をコピーします。
$ sudo cp /usr/share/fonts/truetype/takao-gothic/TakaoGothic.ttf /usr/local/qt5pi/lib/fonts/
Code上にて、導入した日本語フォントのfontfamilyをセットする
- Widgetの場合
QApplicationに対して、QFontクラスにてfontfamilyを指定します。
QApplication a(argc, argv); ・・・ QFont font; // 導入した日本語のフォントファミリーを指定します。 font.setFamily("TakaoGothic"); a.setFont( font ); ・・・
- QMLの場合
Text Elementのfont.familyのPropertiesを指定する。
Text { ・・・ // 導入した日本語のフォントファミリーを指定する。 font.family: "TakaoGothic" //[*] ・・・ }
確認に使ったソース
- main.cpp
#include "mainwindow.h" #include <QApplication> #include <QLabel> #include <QFont> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { QLabel *label = new QLabel("Hello RaspberryPi \n\ こんにちはRaspberryPi"); setCentralWidget(label); } MainWindow::~MainWindow() { } int main(int argc, char *argv[]) { QApplication a(argc, argv); QFont font; // 導入した日本語のフォントファミリーを指定する。 font.setFamily("TakaoGothic"); //[*] font.setPointSize( 48 ); a.setFont( font ); MainWindow w; w.show(); return a.exec(); }
- mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = 0); ~MainWindow(); }; #endif // MAINWINDOW_H
QML版
- Sample_Raspberrypi_Qt5_qml.qml
Rectangle { width: 800 height: 600 Text { anchors.centerIn: parent font.pointSize: 48 // 導入した日本語のフォントファミリーを指定する。 font.family: "TakaoGothic" //[*] text: "Hello RaspberryPi \n こんにちはRaspberryPi" } }
QML実行方法
$ qmlscene ./Sample_Raspberrypi_Qt5_qml.qml