轻量级Qt键盘-中文输入

在原有的键盘基础上新增中文输入功能。

插图

中文候选栏

  中文输入候选栏ChineseWidget使用QListWidget和样式表实现:

setText输入对应拼音字母,即会加载符合的拼音中文。
pressedChanged信号函数即为当按键按下,传递对应的中文。

1
2
3
4
5
6
7
8
9
10
class ChineseWidget : public QListWidget {
Q_OBJECT
public:
ChineseWidget(QWidget *parent = NULL);
void setText(const QString &text);

signals:
void pressedChanged(const int &code, const QString &text);
...
};

  设置QListWidget:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
setFocusPolicy(Qt::NoFocus);
/* 设置为列表显示模式 */
setViewMode(QListView::ListMode);

/* 从左往右排列 */
setFlow(QListView::LeftToRight);

/* 屏蔽水平滑动条 */
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

/* 屏蔽垂直滑动条 */
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

/* 设置为像素滚动 */
setHorizontalScrollMode(QListWidget::ScrollPerPixel);

/* 设置鼠标左键拖动 */
QScroller::grabGesture(this, QScroller::LeftMouseButtonGesture);

/* 设置样式 */
setStyleSheet(R"(
QListWidget { outline: none; border:1px solid #00000000; color: black; }
QListWidget::Item { width: 50px; height: 50px; }
QListWidget::Item:hover { background: #4395ff; color: white; }
QListWidget::item:selected { background: #4395ff; color: black; }
QListWidget::item:selected:!active { background: #00000000; color: black; }
)");

加载中文字库

  字库加载在QMap<QString, QList<QPair<QString, QString>> >容器中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
QFile pinyin(":/ChineseLib/PinYin");
if (! pinyin.open(QIODevice::ReadOnly)) {
qDebug() << "Open pinyin file failed!";
return;
}

while (! pinyin.atEnd()) {
QString buf = QString::fromUtf8(pinyin.readLine()).trimmed();
QRegExp regExp("^[\u4E00-\u9FA5]+");

int index = regExp.indexIn(buf);
if (index == -1)
continue;

QString first = buf.right(buf.size() - regExp.matchedLength()); // 分离拼音字母
QString second = buf.mid(index, regExp.matchedLength()); // 分离中文

QList<QPair<QString, QString>> &tmp = m_data[first.left(1)]; // 取首字母做索引
tmp.append(qMakePair(first, second));
}

  部分字库内容预览:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
安a
按a
爱a
阿a
暗a
啊a
埃a
碍a
凹a
奥a
岸a
矮a
案a
俺a

匹配符合拼音的中文

  取拼音首字母索引,再匹配中文。

1
2
3
4
5
6
7
const QList<QPair<QString, QString>> &tmp = m_data[text.left(1)];
for (const QPair<QString, QString> &each : tmp) {
if (each.first != text) // 匹配是否符合的在容器里面拼音
continue;

addOneItem(each.second);
}

关于更多

  1. 轻量级Qt键盘-介绍篇
  2. 通过索引优化查找性能
  3. 公众号Qt君后台回复『Qt键盘』获取往期推送文章。