実は「さくさくエディタ」は最初、Qt5 の勉強もかねて Qt5.0 で開発し始めたのだが、IME(InputMethod)周りが期待したようには動作せず(いったいどうい問題があったのかは覚えてない)、情報が少なく対処も難しそうだったので Qt4.x に変更した経緯がある。
が、もうバージョンも 5.5 になってて、さすがにいろいろ治ってるだろうと、Qt 5.5 でIME周りの動作確認をしてみたところ、以下のコードでちゃんと動作した。
めでたし、めでたし。
void MainWindow::inputMethodEvent(QInputMethodEvent * event) { QWidget::inputMethodEvent(event); auto pre = event->preeditString(); auto txt = event->commitString(); qDebug() << "inputMethodEvent(): pre = " << pre; qDebug() << "inputMethodEvent(): txt = " << txt; } QVariant MainWindow::inputMethodQuery( Qt::InputMethodQuery query ) const { if( query == Qt::ImCursorRectangle ) { qDebug() << "query == Qt::ImCursorRectangle"; return QVariant(QRect(m_px, m_py, 1, 1)); } return QMainWindow::inputMethodQuery(query); }
まとめ:
- 1文字入力は、keyPressEvent ( QKeyEvent * event ); を再実装する。
- IME イベントを処理したい場合は setAttribute(Qt::WA_InputMethodEnabled); を実行しておく
- IME イベント処理は inputMethodEvent(QInputMethodEvent * event); を再実装する。
- preeditString() で現候補文字を取得
- commitString() で確定文字を取得
- IME 候補ウィンド位置は inputMethodQuery( Qt::InputMethodQuery query ) を再実装する
- query が Qt::ImCursorRectangle の時に、ウィンドウ位置を返す
- 矩形サイズは無視されるようだが、0, 0 を指定すると左上に表示されてしまう
- 実際に表示されるのは文字高さ?分だけ下にずれるようだ