標籤:http os 使用 io ar for art div sp
characterapplicationsignalqtIMEobject
1、從QInputContext派生自己的InputContext類 ,例如:
class MyInputPanelContext : public QInputContext
{
Q_OBJECT
public:
MyInputPanelContext();
~MyInputPanelContext();
/* 事件過濾器 */
bool filterEvent(const QEvent* event);
QString identifierName();
QString language();
bool isComposing() const;
void reset();
private slots:
/* 槽用於接收從輸入面板輸入的字元 */
void sendCharacter(QChar character);
private:
void updatePosition();
private:
/* 關聯的輸入面板 */
MyInputPanel *inputPanel;
};
MyInputPanelContext::MyInputPanelContext()
{
/* 建立和IME關聯的面板 */
inputPanel = new MyInputPanel;
/* 並將characterGenerated和sendCharacter關聯,當使用者按鍵後,則繼續由sendCharacter向目標Widget */
connect(inputPanel, SIGNAL(characterGenerated(QChar)), SLOT(sendCharacter(QChar)));
}
bool MyInputPanelContext::filterEvent(const QEvent* event)
{
if (event->type() == QEvent::RequestSoftwareInputPanel)
{
/* 當某個Widget請求軟鍵盤輸入時,顯示軟鍵盤 */
updatePosition();
inputPanel->show();
return true;
}
else if (event->type() == QEvent::CloseSoftwareInputPanel)
{
/* 當某個Widget請求關閉軟鍵盤輸入時,關閉軟鍵盤 */
inputPanel->hide();
return true;
}
return false;
}
void MyInputPanelContext::sendCharacter(QChar character)
{
QPointer<QWidget> w = focusWidget();
if (!w)
return;
/* 當收到按鍵面板的按鍵輸入後,分別向當前焦點Widget發送KeyPress和KeyRelease事件 */
QKeyEvent keyPress(QEvent::KeyPress, character.unicode(), Qt::NoModifier, QString(character));
QApplication::sendEvent(w, &keyPress);
if (!w)
return;
QKeyEvent keyRelease(QEvent::KeyPress, character.unicode(), Qt::NoModifier, QString());
QApplication::sendEvent(w, &keyRelease);
}
/* 根據當前焦點Widget的位置,調整輸入面板的位置 */
void MyInputPanelContext::updatePosition()
{
QWidget *widget = focusWidget();
if (!widget)
return;
QRect widgetRect = widget->rect();
QPoint panelPos = QPoint(widgetRect.left(), widgetRect.bottom() + 2);
panelPos = widget->mapToGlobal(panelPos);
inputPanel->move(panelPos);
}
2、輸入面板
圖示:
/* 每個按鈕具有一個buttonValue動態屬性,表明和該按鈕相關的字元,當按鈕點擊時,將此字元作為訊號參數發出 */
/* 前面的InputContext關聯了此訊號,並進一步發送給了目標Widget */
void MyInputPanel::buttonClicked(QWidget *w)
{
QChar chr = qvariant_cast<QChar>(w->property("buttonValue"));
emit characterGenerated(chr);
}
3、使用InputContext
在應用程式main處,通過setInputContext將InputContext和Application關聯,入:
int main(int argc, char **argv)
{
QApplication app(argc, argv);
MyInputPanelContext *ic = new MyInputPanelContext;
/* InputContext和Application關聯 */
app.setInputContext(ic);
/* 主視窗 */
QWidget widget;
Ui::MainForm form;
form.setupUi(&widget);
widget.show();
return app.exec();
}
qt軟鍵盤輸入