c++qtqlineedit

Prevent Qt inputMethod from hiding when button is clicked


We are using a QLineEdit and the QGuiApplication::inputMethod()->show() to have a virtual keyboard for user input. There are also buttons (QPushButton) for some sort of suggestions to the user for his/her input, i.e. if a button is clicked text elements are put into the QLineEdit.

However, if the user clicks on a button, the QLineEdit loses focus resulting in the virtual keyboard to disappear. But we don't want the keyboard to disappear when the user clicks on a button.

We've already tried to use the installEventFilter() method and catch the focusOut event of the QLineEdit, but still the keyboard will disappear as soon as the user clicks on a button. We also tried to call the show()/setVisible(true) method of the inputMethod, but it seems like there is another event or signal fired which causes the inputMethod to call its hide slot which makes the keyboard to disappear.

How can we prevent the keyboard to disappear when a button is clicked?

EDIT
Here is a small example. The gui elements were added using the Qt Designer mode of the Qt Creator (Note that ui_mainwindow.h is auto generated by qmake). And it looks like the following picture:
enter image description here

main.cpp

#include "mainwindow.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    qputenv("QT_IM_MODULE", QByteArray("qtvirtualkeyboard"));
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

MainWindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>


QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

    bool eventFilter(QObject *obj, QEvent *ev ) override;

private:
    Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H

MainWindow.cpp (which has the eventFilter method to catch the focusOut event of the QLineEdit)

#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QLineEdit>
#include <iostream>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->lineEdit->installEventFilter(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

bool MainWindow::eventFilter(QObject* obj, QEvent* ev)
{
    auto lineEdit = qobject_cast<QLineEdit*>(obj);
    if(lineEdit && ev->type() == QEvent::FocusOut)
    {
        std::cout << "qlineEdit and FocusOut" << std::endl;
        // neither of the following lines as the desired effect
        //QGuiApplication::inputMethod()->setVisible(true);
        //QGuiApplication::inputMethod()->show();
        return true;
    }
}

Solution

  • We found a solution to the problem! If you set the focus policy of the corresponding buttons to Qt::NoFocus the virtual keyboard won't disappear when a button is clicked!