QT 软键盘

1.需要做如下的界面

2. .h文件

 1 #ifndef KEYBOARD_H
 2 #define KEYBOARD_H
 3 
 4 #include <QWidget>
 5 #include <QMessageBox>
 6 #include <QList>
 7 #include <QToolButton>
 8 #include <QSignalMapper>
 9 #include <QKeyEvent>
10 namespace Ui {
11 class keyBoard;
12 }
13 
14 class keyBoard : public QWidget
15 {
16     Q_OBJECT
17 
18 public:
19     explicit keyBoard(QWidget *parent = 0);
20     ~keyBoard();
21     QString lineText;                //编辑的内容
22     void lineSetFocus();             //光标的位置
23 private:
24        QWidget *m_pParent;
25        int i;
26        QSignalMapper *signalMapper;
27        QList<QToolButton *> allButtons;
28 private slots:
29        void on_btnClear_clicked();                 //清除按键
30        void on_btnHide_clicked();                  //取消按键
31        void on_btnEnter_clicked();                 //确定按键
32        void toolButton(int btn);                   //所有按键
33 private:
34     Ui::keyBoard *ui;
35 };
36 
37 #endif // KEYBOARD_H
View Code

3. .cpp文件

 1 #include "keyboard.h"
 2 #include "ui_keyboard.h"
 3 #include <QDebug>
 4 keyBoard::keyBoard(QWidget *parent) :
 5     QWidget(parent),
 6     ui(new Ui::keyBoard)
 7 {
 8     ui->setupUi(this);
 9     m_pParent = parent;
10     signalMapper = new QSignalMapper(this);
11     allButtons = findChildren<QToolButton *>();
12     for( i=0;i<allButtons.count();i++) {
13      //signalMapper多信号跟同一槽链接
14         connect(allButtons.at(i), SIGNAL(clicked()), signalMapper, SLOT(map()));
15         signalMapper->setMapping(allButtons.at(i), i);
16     }
17     connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(toolButton(int)));
18 }
19 
20 keyBoard::~keyBoard()
21 {
22     delete ui;
23 }
24 
25 void keyBoard::lineSetFocus() //设置光标
26 {
27     ui->lineEdit->setFocus();
28 
29 }
30 
31 void keyBoard::toolButton(int btn){
32       QString strKeyId;
33       strKeyId = allButtons.at(btn)->accessibleName(); //获取按钮的属性标识
34       bool isOk;
35       int keyId = strKeyId.toInt(&isOk, 16); //将16进制转化成10进制
36       if (strKeyId.isEmpty() || !isOk) {
37           return;
38       }
39     int involvedKeys = 1;
40     Qt::KeyboardModifiers Modifier = Qt::NoModifier;
41     QString ch = allButtons.at(btn)->text().trimmed();
42     if (keyId==Qt::Key_Space){
43         ch = " ";
44     }
45     //描述键盘按键所产生的QT事件
46     //参数type必须是QEvent::KeyPress, QEvent::KeyRelease, or QEvent::ShortcutOverride
47     QKeyEvent keyEvent(QEvent::KeyPress, keyId, Modifier, ch, false, involvedKeys);
48     QApplication::sendEvent(this->focusWidget(),&keyEvent);
49 }
50 
51 void keyBoard::on_btnEnter_clicked() //确定并返回键
52 {
53    lineText=ui->lineEdit->text();
54    this->hide();
55 }
56 
57 void keyBoard::on_btnHide_clicked() //取消键
58 {
59     this->hide();
60 }
61 
62 void keyBoard::on_btnClear_clicked() //清除键
63 {
64     ui->lineEdit->setText("");
65 }
View Code

 

posted on 2018-07-12 17:22  小小小哈  阅读(5357)  评论(0编辑  收藏  举报

导航