【更新】
2012-7-9,设计模式(5)-装饰模式(Decorator),运用装饰模式改进的版本
2012-6-6,设计模式(1)-模板模式,运用模板模式改进的版本
2012-5-29,添加源码示例下载地址(文章末尾)
【描述】
用QT制作了输入法,能输入英文和数字以及字符。简要介绍,示出关键代码。在QLineEdit控件和QTableWidget中均可以使用,本例只给出了QLineEdit的情况。
【效果】
单击编辑框控件,跳出输入法。如图1所示:
图1 输入法效果
图2 开发板运行效果
【原理】将QToolButton控件上的字符,传给需要输入的控件。
【简介】
先利用QT Creator设计一个键盘界面,如图2所示:
图2 设计键盘界面
以字符为'q’的按钮为例,将对象命名为toolButton_q,以此类推。
【关键代码】
keyboard.h
#ifndef KeyBoard_H
#define KeyBoard_H
#include <QtGui>
#include <QSignalMapper>
#include "ui_keyboard.h"
enum {
iMode_Normal = 0,
iMode_Passwd = 1
};
namespace Ui {
class KeyBoard;
}
class KeyBoard : public QDialog, Ui::KeyBoard
{
Q_OBJECT
public:
KeyBoard();
~KeyBoard();
//void mouseMoveEvent(QMouseEvent *);
//void mousePressEvent(QMouseEvent *);
public:
QString text;
private:
QSignalMapper *signalMapper;
QPoint dragPosition;
bool caps_Lock;
int inputMode;
bool waitingForOperand;
private:
void setMapper();
void connectMapper();
signals:
void setvalue(const QString &);
private slots:
void onCursorRight();
void onCursorLeft();
void onCursorUp();
void onCursorDown();
void onHorizontalSliderValueChanged(int value);
void setDispText(const QString& text);
void onInvMode();
void onCapslock();
void onEnter();
void onBackspace();
void onEsc();
};
#endif // KeyBoard_H
keyboard.cpp
#include <QtGui>
#include "keyboard.h"
KeyBoard::KeyBoard()
{
setupUi(this);
setWindowFlags(Qt::Tool|Qt::WindowStaysOnTopHint|Qt::FramelessWindowHint);
display->setFocus();
waitingForOperand = true;
inputMode = iMode_Normal;
caps_Lock = false;
signalMapper=new QSignalMapper(this);
setMapper();
connectMapper();
connect(signalMapper,SIGNAL(mapped(const QString&)),this,SLOT(setDispText(const QString&)));
connect(toolButton_up,SIGNAL(clicked()),this,SLOT(onCursorUp()));
connect(toolButton_down,SIGNAL(clicked()),this,SLOT(onCursorDown()));
connect(toolButton_right,SIGNAL(clicked()),this,SLOT(onCursorRight()));
connect(toolButton_left,SIGNAL(clicked()),this,SLOT(onCursorLeft()));
connect(toolButton_Inv,SIGNAL(clicked()),this,SLOT(onInvMode()));
connect(toolButton_enter,SIGNAL(clicked()),this,SLOT(onEnter()));
connect(toolButton_backspace,SIGNAL(clicked()),this,SLOT(onBackspace()));
connect(toolButton_capslock,SIGNAL(clicked()),this,SLOT(onCapslock()));
connect(toolButton_esc,SIGNAL(clicked()),this,SLOT(onEsc()));
connect(horizontalSlider,SIGNAL(valueChanged(int)),this,SLOT(onHorizontalSliderValueChanged(int)));
}
KeyBoard::~KeyBoard()
{
}
/*
* Name : void mouseMoveEvent(QMouseEvent *event),void mousePressEvent(QMouseEvent *event)
* Type : QEvent
* Func : realize drag the window of keyBoard by mouse press and move
* In : QMouseEvent
* Out : Null
*/
/*
void KeyBoard::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() == Qt::LeftButton)
{
move(event->globalPos() - dragPosition);
event->accept();
}
}
void KeyBoard::mousePressEvent(QMouseEvent *event)
{
if (event->button