步骤
1.制作界面
QToolbutton
2.为需要使用到软键盘的控件添加事件过滤器
ui->userEdit->installEventFilter(this);
ui->passwordEdit->installEventFilter(this);
2、重写eventFilter事件,判断当前触发对象是否是添加了过滤器的控件,且事件是否是鼠标按钮点击事件。是的话,显示软键盘,并将焦点设置到当前控件上
bool softkey::eventFilter(QObject *watched, QEvent *event)
{
if ( (watched == ui->userEdit) && (event->type() == QEvent::MouseButtonPress) )
{
ui->myWidget->show();
ui->userEdit->setFocus();
}
else if ( (watched == ui->passwordEdit) && (event->type() == QEvent::MouseButtonPress) )
{
ui->myWidget->show();
ui->passwordEdit->setFocus();
}
return QMainWindow::eventFilter(watched,event);
}
3.若是当前控件编辑完毕则隐藏软键盘
重写类mylabel自定义信号close_key,当判断当前事件是鼠标点击,则发散close_key信号,并且返回true,Qt 会认为这个事件已经处理完毕,不会再将这个事件发送给其它对象。
class mylabel : public QLabel
{
Q_OBJECT
public:
explicit mylabel(QWidget *parent = Q_NULLPTR);
bool event(QEvent *e) override
{
if(e->type() == QEvent :: MouseButtonPress){
emit close_key();
return true;
}
return QLabel::event(e);
}
signals:
void close_key();
};
connect(ui->backgroundlabel,&mylabel::close_key,this,&softkey::hide_widget);
void softkey::hide_widget()
{
ui->myWidget->hide();
}
4、在自定义按钮类softKey的槽函数中判断当前点击的按钮文本,定义一个按键事件,通过postEvent将事件key发送出去
softkeys::softkeys(QWidget *parent) : QToolButton(parent)
{
connect(this,SIGNAL(clicked(bool)),this,SLOT(button_clicked(bool)));
}
void softkeys::button_clicked(bool)
{
//this->text() ----获得控件上的文本内容,比如,删除
if(this->text() == "<-")
{
//定义一个事件,Key_Backspace撤消按钮
QKeyEvent* key = new QKeyEvent(QEvent::KeyPress,Qt::Key_Backspace,Qt::NoModifier, this->text());
//通过postEvent将事件key发送出去给QApplication::focusWidget(),
//在当前窗口界面中有焦点的控件
QApplication::postEvent(QApplication::focusWidget(),key);
}else
{
QKeyEvent* key = new QKeyEvent(QEvent::KeyPress,'w',Qt::NoModifier, this->text());
//通过postEvent将事件key的文本内容发送出去,QApplication::focusWidget()当前窗口中,有光标的
//控件上
QApplication::postEvent(QApplication::focusWidget(),key);
}
}
5.更改控件属性
需要将QToolButton的属性改成softkeys,因为自定义了软键盘的类,因此需要将按钮属性设置为你自定义的类,才能有效果。
同理,自定义了mylabel的类,需要将背景label的属性从QLabel改为mylabel
具体操作示例
右键
最终软键盘效果图
附上github源代码:
https://github.com/blackyue/QtUi
参考链接:
https://blog.youkuaiyun.com/bangtanhui/article/details/116497414
https://www.jianshu.com/p/48f007c2de09