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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM