2
votes

I'm creating a simple virtual keyboard in a QDockWidget...
When the widget is docked into the QMainWindow, the selected widget (for example a qdoublespinbox) is highlighted and if I click on the virtual keyboard clearFocus() works...

When the QDockWidget is floating above the window and I click a button, clearFocus doesn't work and I can't see the focused widget in QMainWindow...

How can I force the QDockWidget to not have any focus at all?

Thanks :-)

This is the code:

// class MyVirtualKeyboard : public QDockWidget

void MyVirtualKeyboard::sendKey(Qt::Key key, Qt::KeyboardModifier mod)
{
    this->clearFocus();

    QMainWindow *w = dynamic_cast<QMainWindow *>(this->parent());
    if(w == NULL) return;

    QWidget *widget = w->focusWidget();

    QString repr = QKeySequence(key).toString();

    QKeyEvent *pressEvent = new QKeyEvent(QEvent::KeyPress, key, mod, repr);
    QKeyEvent *releaseEvent = new QKeyEvent(QEvent::KeyRelease, key, mod, repr);

    qDebug("%s", pressEvent->text().toAscii().data());

    MyApplication *app = MyApplication::myInstance();

    app->postEvent(widget, pressEvent);
    app->postEvent(widget, releaseEvent);
}

void MyVirtualKeyboard::on_BTN_1_clicked()
{
    sendKey(Qt::Key_1);
}

...
4

4 Answers

2
votes

The clearFocus() call should be unnecessary. Your dock widget and all of its widgets must have the Qt::NoFocus policy.

The code below shows how you might do it.

screenshot

// https://github.com/KubaO/stackoverflown/tree/master/questions/vkb-focus-18558664
#include <QtGui>
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
#include <QtWidgets>
#endif

class Keyboard : public QDockWidget {
   Q_OBJECT
   QWidget m_widget;
   QGridLayout m_layout{&m_widget};
   QToolButton m_buttons[10];
   void sendKey(Qt::Key key, Qt::KeyboardModifier mod)
   {
      if (! parentWidget()) return;
      auto target = parentWidget()->focusWidget();
      if (! target) return;

      auto repr = QKeySequence(key).toString();
      auto pressEvent = new QKeyEvent(QEvent::KeyPress, key, mod, repr);
      auto releaseEvent = new QKeyEvent(QEvent::KeyRelease, key, mod, repr);
      qApp->postEvent(target, pressEvent);
      qApp->postEvent(target, releaseEvent);
      qDebug() << repr;
   }
   Q_SLOT void clicked() {
      auto key = sender()->property("key");
      if (key.isValid()) sendKey((Qt::Key)key.toInt(), Qt::NoModifier);
   }
public:
   explicit Keyboard(const QString & title, QWidget *parent = nullptr) : Keyboard(parent) {
      setWindowTitle(title);
   }
   explicit Keyboard(QWidget *parent = nullptr) : QDockWidget(parent) {
      int i{};
      for (auto & btn : m_buttons) {
         btn.setText(QString::number(i));
         btn.setProperty("key", Qt::Key_0 + i);
         m_layout.addWidget(&btn, 0, i, 1, 1);
         connect(&btn, SIGNAL(clicked()), SLOT(clicked()));
         btn.setFocusPolicy(Qt::NoFocus);
         ++i;
      }
      setWidget(&m_widget);
      setFeatures(QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable);
   }
};

int main(int argc, char ** argv)
{
   QApplication a(argc, argv);
   QMainWindow w;
   w.setCentralWidget(new QLineEdit);
   w.addDockWidget(Qt::TopDockWidgetArea, new Keyboard("Keyboard", &w));
   w.show();
   return a.exec();
}

#include "main.moc"
1
votes

You can prevent a widget from taking focus by setting QWidget::focusPolicy = Qt::NoFocus.

However, there are two concepts here that you're mixing - the focused control (per window), and the active window (per desktop). I think in the scenario you're describing (a torn-off popup window), the OS window manager is likely to still change the active top-level window even if Qt doesn't set a focused control. That will result in nobody having keyboard focus (which is a valid state!).

So I think a full answer to your question will involve some non-portable bits. I don't know what GUI environment you're working in, but I know some of the answer for Win32, so I'll keep going and hope that's useful:

Win32

There's a pretty good discussion of the state tracking for Win32 on MSDN in the article Win32 Activation and Focus. I'm not aware that Qt does anything to wrap this level, so you'd have to use QWidget::nativeEvent or QCoreApplication::installNativeEventFilter to get at the low-level event. If you can subclass the window, I'd prefer the former, since it's more self-contained.

bool FooWidget::nativeEvent(const QByteArray & eventType, void * message, long * result)
{
#ifdef Q_OS_WIN
    if(eventType == "windows_generic_MSG") {
        const MSG *msg = reinterpret_cast<MSG *>(message);
        if(msg->message == WM_MOUSEACTIVATE) {
            *result = MA_NOACTIVATE;
            return true;
        }
    }
#else
    #error Need platform-specific code to suppress click-activation
#endif
    return false;
}

This should block the click from activating the window (MA_NOACTIVATE), and block Qt from processing it further (return true), while leaving other all events (including the the click, since we didn't use MA_NOACTIVATEANDEAT to block it too) to be processed into QEvents and Qt signals normally (return false at the end).

If you need further low-level access (though I don't think you will), see also QWidget::effectiveWinId() and QWidget::windowHandle

0
votes

Thanks a lot to Martin Gräßlin for the answer!

My recommendation: check out the virtual keyboard code in KDE Plasma: http://quickgit.kde.org/?p=kdeplasma-addons.git&a=blob&h=5628d6325afe57f85917dad865a07d4116335726&hb=a658d1e257cfca2a43c12714d026ec26f1fdb755&f=applets%2Fplasmaboard%2Fwidget.cpp

Looks like the key is setWindowFlags(Qt::X11BypassWindowManagerHint) and setFocusPolicy(Qt::NoFocus)

MyVirtualKeyboard::MyVirtualKeyboard(QWidget *parent) :
    QDockWidget(parent),
    ui(new Ui::MyVirtualKeyboard)
{
    ui->setupUi(this);

    this->connect(this, SIGNAL(topLevelChanged(bool)), this, SLOT(topLevelChanged()));
}

void MyVirtualKeyboard::topLevelChanged()
{
    if(this->isWindow())
    {
        this->setWindowFlags(Qt::Popup | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint);
        this->setFocusPolicy(Qt::NoFocus);
        this->show();
    }
}
0
votes

I think I've found a better way to do it! Just use this->setAttribute(Qt::WA_X11DoNotAcceptFocus); and voila!

Example:

MyVirtualKeyboard::MyVirtualKeyboard(QWidget *parent) :
    QDockWidget(parent),
    ui(new Ui::MyVirtualKeyboard)
{
    ui->setupUi(this);
    this->setAttribute(Qt::WA_X11DoNotAcceptFocus);
}