qt 弹框中的QLineEdit无法输入

本文介绍了如何修复Qt中的QWidget对话框中QLineEdit控件在获得焦点时无法输入字母和数字的问题,通过安装焦点事件过滤器并正确处理FocusIn和FocusOut事件实现中文输入正常而英文输入禁用。
摘要由CSDN通过智能技术生成

主界面中按钮弹出QWidget框,此时弹框上的QLineEdit无法输入字母和数字,我的是可以输入中文

解决方法:第一步QLineEdit安装焦点事件:(以两个QLineEdit控件为例)

ui->lineEdit_2->installEventFilter(this);

ui->lineEdit_3->installEventFilter(this);

第二步获取焦点事件并使QLineEdit控件获取键盘输入

bool CFuturesTradeLogin::eventFilter(QObject *watched, QEvent *event)
{
    if(watched == ui->lineEdit_2)
    {
        if(event->type() == QEvent::FocusIn)
        {
            ui->lineEdit_2->grabKeyboard();
        }
        else if(event->type() == QEvent::FocusOut)
        {
        }
    }
    else if(watched == ui->lineEdit_3)
    {
        if(event->type() == QEvent::FocusIn)
        {
            ui->lineEdit_3->grabKeyboard();
        }
        else if(event->type() == QEvent::FocusOut)
        {
        }
    }
    return QWidget::eventFilter(watched, event); // 最后将事件交给上层对话框
}

ui->lineEdit_2和ui->lineEdit_3不能同时获取键盘输入,只给获取焦点的输入框键盘输入的功能

效果如下

 

  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以通过调用Qt的虚拟键盘来实现在QLineEdit输入文本的功能。具体步骤如下: 1. 在Qt创建一个QLineEdit控件。 2. 在QLineEdit控件上设置一个单击事件,当用户单击该控件时,触发此事件。 3. 在单击事件,调用Qt的虚拟键盘,使其弹出。 4. 当用户在虚拟键盘上输入文本后,将文本传递给QLineEdit控件。 下面是一个示例代码: ```cpp #include <QApplication> #include <QLineEdit> #include <QVBoxLayout> #include <QKeyEvent> #include <QPushButton> class MyLineEdit : public QLineEdit { public: MyLineEdit(QWidget *parent = nullptr) : QLineEdit(parent) {} protected: void keyPressEvent(QKeyEvent *event) override { QLineEdit::keyPressEvent(event); QString text = event->text(); if (!text.isEmpty()) { insert(text); } } }; int main(int argc, char *argv[]) { QApplication app(argc, argv); QWidget widget; QVBoxLayout *layout = new QVBoxLayout(&widget); MyLineEdit *lineEdit = new MyLineEdit(); QPushButton *button = new QPushButton("Open Virtual Keyboard"); QObject::connect(button, &QPushButton::clicked, [&] { QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_unknown, Qt::NoModifier, "", false, 0); QCoreApplication::sendEvent(lineEdit, &keyPress); }); layout->addWidget(lineEdit); layout->addWidget(button); widget.show(); return app.exec(); } ``` 在这个示例,我们自定义了一个MyLineEdit控件,重写了它的keyPressEvent()函数。在keyPressEvent()函数,我们获取了用户在虚拟键盘上输入的文本,并将其插入到QLineEdit控件。 在主函数,我们创建了一个QVBoxLayout布局,并将MyLineEdit控件和一个QPushButton控件添加到该布局。当用户单击QPushButton控件时,我们使用QCoreApplication::sendEvent()函数将一个虚拟按键事件发送到MyLineEdit控件,从而触发虚拟键盘的弹出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值