QT备忘录之十一:手搓一个Popup风格的简单输入框

最近打算用到一个单一参数的录入,想要用个瞬态交互(即没有显式的确认按钮,输入窗口失去焦点则自动提交)的方式。本来打算直接用QInputDialog,却发现setWindowFlags设置为Qt::Popup后,输入框中居然无法响应中文输入法,于是又手搓了一把。【本文的部分调研和数据整理工作借助AI工具完成】

0. 关于Qt::Popup

Qt::Popup 是 Qt 框架中一个历史悠久的窗口标志(Window Flag),专门用于创建弹出式顶层窗口。其设计目标,是实现菜单(Menu)和下拉列表(Dropdown)这类交互模式。即:

  • 轻量的模态对话框:它是一个顶层窗口,但相比 Qt::Dialog,它的“模态”更温和,通常只阻塞与它关联的父窗口的部分交互,而不是整个应用。
  • 自动且可靠地关闭:只要用户点击窗口以外的任何地方,Qt::Popup 就会自动关闭。而这个行为是 Qt 框架内部强制保证的。

所以理论上说,在Qt中实现一个“焦点离开即关闭”的悬浮单值设置窗,直接使用QInputDialog并将setWindowFlags设置为 Qt::Popup 就行了。

1. 关于Qt::Popup对话框无法响应中文输入法的研究

1.1 IME原理简析

IME是Input Method Editor(输入法编辑器)的缩写,其本质是一个把输入事件转换成目标语言文字的系统组件。一般来说,IME是系统输入框架的一部分。OS调度IME执行事务的流程大致如下:

  • 应用把按键事件交给系统。
  • 系统判断当前 IME 是否处理。
  • IME 通过 API 获取光标位置、周围文本、输入上下文。
  • 用户选词后,IME 调用客户端 API 提交字符串。
  • 应用收到的是最终文本,而不是每个按键。

具体到不同的OS,分别通过以下输入框架/管理器实现对输入法的支持:

  • Windows:TSF / IMM32
  • macOS:InputMethodKit
  • Linux:IBus、Fcitx
  • Android:InputMethodService
  • iOS:Keyboard Extension

1.2 为什么IME在Qt::Popup失效了?

IME 通常在后台待命,以便在合适的时候被系统路由到输入事件。系统对一下条件进行判断:

  • 当前焦点是不是文本框、搜索框、编辑区。
  • 当前激活的输入源是不是这个 IME。
  • 这个按键是否属于文本输入。
  • 是否处于组合输入状态。

只有这些条件匹配时,键盘事件才会传递给IME,显示预编辑串和候选词。现在在Qt::Popup的QLineEdit中,直接出现了英文字母(就好像没有开启中文输入法一样),很显然是输入事件没有路由到这个对话框,即便是加上了WA_InputMethodEnabled 也不能解决。为什么呢?来看代码。

// qwidget.cpp line: 6580-6593
void QWidgetPrivate::setFocus_sys()
{
    Q_Q(QWidget);
    // Embedded native widget may have taken the focus; get it back to toplevel if that is the case
    const QWidget *topLevel = q->window();
    if (topLevel->windowType() != Qt::Popup) {
        if (QWindow *nativeWindow = q->window()->windowHandle()) {
            if (nativeWindow != QGuiApplication::focusWindow()
                && q->testAttribute(Qt::WA_WState_Created)) {
                nativeWindow->requestActivate();
            }
        }
    }
}

任何普通窗口内的 widget 获得焦点时,都会对其顶层原生窗口调用 requestActivate();唯独 Qt::Popup 被排除。因此 Popup 的原生窗口永远不会成为 QGuiApplication::focusWindow(),OS 层面的窗口焦点仍停留在父窗口上。

// qapplication.cpp line: 3915-3928
    if (QApplicationPrivate::popupWidgets->count() == 1) // grab mouse/keyboard
        grabForPopup(popup);

    // popups are not focus-handled by the window system (the first
    // popup grabbed the keyboard), so we have to do that manually: A
    // new popup gets the focus
    if (popup->focusWidget()) {
        popup->focusWidget()->setFocus(Qt::PopupFocusReason);

popup 通过 grabForPopup 主动抓取,让按键事件路由到 popup,同时调用 setFocus(Qt::PopupFocusReason) 维持焦点。这解释了popup窗口能接收到键盘事件。

// qwidget.cpp line: 6826-6830 
bool QWidget::isActiveWindow() const{
    QWidget *tlw = window();
    if(tlw == QApplication::activeWindow() || (isVisible() && (tlw->windowType() == Qt::Popup)))
        return true;

焦点切换时,isActiveWindow()在popup时永远返回true(相当于是个伪造的信号)。

// qwidget.cpp line: 6515-6518
            if (reason != Qt::PopupFocusReason && reason != Qt::MenuBarFocusReason
                && prev->testAttribute(Qt::WA_InputMethodEnabled)) {
                QGuiApplication::inputMethod()->commit();
            }

对 IME 的处理则旁通了 PopupFocusReason。

综上,与 WA_InputMethodEnabled 相关的逻辑看起来一切正常,但popup的原生窗口从未被真实激活,输入法上下文仍关联在父窗口上,因此popup有焦点、能收键鼠时间,IME 却无法触发。

2. 重造一个popup

根据上述的结论,在不改Qt源码的情况下,基于Qt::Popup的窗口无论如何无法与IME交互,因此所有基于Qt::Popup的尝试注定都是徒劳。拆解一下最初的需求:

  • 一个简易、置顶的输入窗口,用于输入参数(类似QLineEdit)且需要支持IME
  • 失去焦点时自动关闭/隐藏
  • 支持形如QDialog::exec的便捷调用方式

针对以上三点真需求,对应的约束和实现路径如下:

  • 直接使用QLineEdit作为窗口部件,或者继承QLineEdit执行改造;支持IME意味着不能使用原生的QWidget::setWindowFlags(Qt::Popup);
  • 失焦时自动关闭或隐藏,需要有一个父窗口来接收失去的焦点;
  • QDialog::exec意味着对话框本身需要有消息循环,并且强制置顶。

于是产生了一个矛盾点:

  • 如果使用强制置顶的模态对话框,将阻断父窗口的消息循环,那么父窗口在本模态窗口退出前,将无法接收到点击鼠标产生的设置焦点事件;
  • 父窗口无法接收到点击鼠标产生的设置焦点事件,也就无法根据焦点事件主动关闭模态对话框

完美死锁。于是空留一个再也无法关闭的模态置顶输入框在风中摇曳。

为了解决这个矛盾,创建输入框之前,必须要创建一个可以全局/全屏接收鼠标事件的对象(QObject或者QWidget),而后以此为父对象再创建输入框。很容易想到,一个透明的全屏父窗口会是输入窗合适的父对象。示例代码如下:

#include <QDialog>
#include <QLineEdit>
#include <QVBoxLayout>
#include <QMouseEvent>
#include <QTimer>
#include <QDebug>

class FloatingOverlayDialog : public QDialog
{
    Q_OBJECT
public:
    explicit FloatingOverlayDialog(QWidget *parent)
        : QDialog(parent), m_lineEdit(nullptr)
    {
        // 1. 设置为无边框、置顶、透明背景
        setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog | Qt::WindowStaysOnTopHint);
        setAttribute(Qt::WA_TranslucentBackground);
        setModal(true); // 模态阻塞,但父窗口被禁用不影响我们捕获点击

        // 2. 拉伸对话框以完全覆盖父窗口客户区
        //    注意:必须用 parent->geometry() 获取父窗口在屏幕上的矩形
        QRect parentRect = parent->geometry();
        setGeometry(parentRect);
        // 移动到父窗口的屏幕坐标位置(因为 geometry 是相对于屏幕的,但 move 需要的也是屏幕坐标)
        move(parent->mapToGlobal(QPoint(0, 0)));

        // 3. 创建真正的输入框,放置在鼠标光标附近
        m_lineEdit = new QLineEdit(this);
        QPoint cursorPos = QCursor::pos();
        // 将鼠标全局坐标转为相对于当前对话框(this)的局部坐标
        QPoint localPos = mapFromGlobal(cursorPos);
        // 让输入框出现在鼠标位置向右偏移 10px 处
        m_lineEdit->setGeometry(localPos.x() + 10, localPos.y() - 15, 120, 30);
        m_lineEdit->setStyleSheet("background: white; border: 1px solid #aaa; border-radius: 3px; padding: 2px;");
        m_lineEdit->setFocus();
        m_lineEdit->selectAll();
        connect(m_lineEdit, &QLineEdit::returnPressed, this, &QDialog::accept);

        // 4. (可选)设置输入校验等
        // m_lineEdit->setValidator(new QDoubleValidator(this));

        // 调试:打印窗口尺寸,确认覆盖范围
        qDebug() << "Overlay geometry:" << geometry() << "Parent rect:" << parentRect;
    }

    // 重写鼠标点击事件:点击透明区域(即输入框以外的区域)即关闭
    void mousePressEvent(QMouseEvent *event) override
    {
        // 注意:如果点击到 m_lineEdit,这个事件不会触发(因为子控件优先处理了)
        // 所以这里只要触发,就说明点击的是外部空白区域,直接关闭
        qDebug() << "Clicked outside the line edit, closing...";
        reject(); // 关闭并返回 Rejected
        QDialog::mousePressEvent(event);
    }

    // 静态便捷方法:弹窗并阻塞获取数值
    static double getValue(QWidget *parent, double defaultVal = 0.0, double fallback = 0.0)
    {
        FloatingOverlayDialog dlg(parent);
        dlg.m_lineEdit->setText(QString::number(defaultVal));
        
        // 确保输入框在全屏覆盖层中可见且获得焦点
        dlg.m_lineEdit->setFocus();
        dlg.m_lineEdit->selectAll();

        int ret = dlg.exec(); // 模态阻塞

        if (ret == QDialog::Accepted) {
            return dlg.m_lineEdit->text().toDouble();
        } else {
            return fallback;
        }
    }

private:
    QLineEdit *m_lineEdit;
};

想法很完美,现实很残酷。QDialog全透明之后,实测捕获不到mouseEvent。继续看源码。

// qwidget.cpp line1450-1455
   QSurfaceFormat format = win->requestedFormat();
    if ((flags & Qt::Window) && win->surfaceType() != QSurface::OpenGLSurface
            && q->testAttribute(Qt::WA_TranslucentBackground)) {
        format.setAlphaBufferSize(8);
    }
    win->setFormat(format);
// ......
// qwidget.cpp line11263-11269
    case Qt::WA_TranslucentBackground:
        if (on) {
            setAttribute(Qt::WA_NoSystemBackground);
            d->updateIsTranslucent();
        }

        break;

WA_NoSystemBackground 意味着系统背景画刷被禁用;一个没有子控件、也没有 paintEvent 重绘的 QDialog,其 backing store 全部像素的 alpha = 0(全透明)。

// qwindowswindow.cpp line341-358
// Set the WS_EX_LAYERED flag on a HWND if required. This is required for
// translucent backgrounds, not fully opaque windows and for
// Qt::WindowTransparentForInput (in combination with WS_EX_TRANSPARENT).
bool QWindowsWindow::setWindowLayered(HWND hwnd, Qt::WindowFlags flags, bool hasAlpha, qreal opacity)
{
    const LONG exStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
    const bool needsLayered = (flags & Qt::WindowTransparentForInput)
        || (hasAlpha && (flags & Qt::FramelessWindowHint)) || opacity < 1.0;

WS_EX_LAYERED 就是“translucent backgrounds”所必需的。

// qwindowsbackingstore.cpp line84-109
    const bool hasAlpha = rw->format().hasAlpha();
    const Qt::WindowFlags flags = window->flags();
    if ((flags & Qt::FramelessWindowHint) && QWindowsWindow::setWindowLayered(rw->handle(), flags, hasAlpha, rw->opacity()) && hasAlpha) {
        // Windows with alpha: Use blend function to update.
        ...
        BLENDFUNCTION blend = {AC_SRC_OVER, 0, BYTE(qRound(255.0 * rw->opacity())), AC_SRC_ALPHA};
        if (QWindowsContext::user32dll.updateLayeredWindowIndirect) {
            ...
            UPDATELAYEREDWINDOWINFO info = {sizeof(info), NULL, &ptDst, &size, m_image->hdc(), &ptSrc, 0, &blend, ULW_ALPHA, &dirty};
            const BOOL result = QWindowsContext::user32dll.updateLayeredWindowIndirect(rw->handle(), &info);
        ...
        QWindowsContext::user32dll.updateLayeredWindow(rw->handle(), NULL, &ptDst, &size, m_image->hdc(), &ptSrc, 0, &blend, ULW_ALPHA);

flush() 检测到 FramelessWindowHint + hasAlpha 后,走 UpdateLayeredWindow(ULW_ALPHA) 路径,把整块 QImage(其中全是 alpha=0 的像素)作为逐像素 alpha 的层窗口内容交给系统。而Win32 对 逐像素 alpha 分层窗口的命中测试(hit-testing)规则是:alpha 值为 0 的像素不参与命中,鼠标消息穿透到下层窗口(Microsoft 文档 "Layered Windows":"Hit testing of a layered window is based on the shape and transparency of the window... areas of the window whose alpha value is zero will let the mouse messages through.")。

那么,如果alpha是一个非常接近0,但是不等于0的值,结果如何呢?

    QDialog::setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);
    QDialog::setAttribute(Qt::WA_TranslucentBackground);

    QVBoxLayout *pLayoutMain = new QVBoxLayout(this);
    pLayoutMain->setSpacing(0);
    QWidget *pWidgetMain = new QWidget(this);
    pWidgetMain->setAttribute(Qt::WA_TranslucentBackground, false);
    pWidgetMain->setStyleSheet("background-color: rgba(0, 0, 0, 0.01);");
    pLayoutMain->addWidget(pWidgetMain);

    m_pLineValue = new QLineEdit(this);
    m_pLineValue->setMinimumSize(128, 32);
    m_pLineValue->move(mapFromGlobal(QCursor::pos()));
    m_pLineValue->setAttribute(Qt::WA_TranslucentBackground, false);
    m_pLineValue->setFocus();

看下效果:

确实可以完全满足上述的三点需求。我把StyleSheet改为background-color: rgba(0, 0, 0, 0.5),效果是这样的:

原理上,就是用了一个QWidget作为全屏遮罩,并以此为父对象在光标位置绘制一个QLineEdit作为输入框。当透明度设的足够小时,视觉上已是一个全透明的对象,但是鼠标、键盘事件不穿透。这个效果日常使用完全够。

 

二零二六年十月十二日

顾毅写于厦门