【问题标题】:Reliable way to detect when a QWidget loses focus?检测 QWidget 何时失去焦点的可靠方法?
【发布时间】:2016-01-14 23:45:11
【问题描述】:

起初,它似乎与this question 重复,但该解决方案对我不起作用。看起来我做的一切都是正确的,但我没有在 LabelledTextEdit::focusOutEvent():

class LabelledTextEdit : public QWidget
{
    Q_OBJECT
public:
    explicit LabelledTextEdit(QString label, int labelheight, int left, int top, int width, int height, QWidget* parent = 0);
    const QStringList getLines() const;
    QLabel* label;
    QPlainTextEdit* text;

protected:
    void focusOutEvent(QFocusEvent* e) override;

signals:
    void doneEditing(const QStringList& lines);
};



LabelledTextEdit::LabelledTextEdit(QString labeltext, int labelheight, int left, int top, int width, int height, QWidget* parent) :
    QWidget(parent)
{
    setGeometry(left, top, width, height);
    setFocusPolicy(Qt::StrongFocus);

    label = new QLabel(labeltext, this);
    //continue setting up label
    label->setGeometry(
                0,              //Left
                0,              //Top
                width,          //Width
                labelheight     //Height
                );
    text = new QPlainTextEdit(this);
    //continue setting up text
    text->setGeometry(
                0,                      //Left
                labelheight,            //Top
                width,                  //Width
                height - labelheight    //Height
                );
}

const QStringList LabelledTextEdit::getLines() const
{
    return text->toPlainText().split('\n', QString::SplitBehavior::KeepEmptyParts);
}

void LabelledTextEdit::focusOutEvent(QFocusEvent* e)
{
    QWidget::focusOutEvent(e);  //breakpoint here is not hit
    if(e->lostFocus())
    {
        emit doneEditing(getLines());
    }
}

我做错了什么?


更新:

感谢 Stuart 建议将 QPlainTextEdit 子类化并将 focusOutEvent() 函数放在那里。这被调用了,但现在我看到了

  1. e->lostFocus() 在获得和失去焦点时返回 true。
  2. 我连接到 doneEditing 信号的槽没有被调用。

【问题讨论】:

  • 我认为这可能是因为它实际上是 QPlainTextEdit 获得了焦点。您可以从 QPlainTextEdit 创建一个派生类,并在其中覆盖焦点更改事件。

标签: c++ qt event-handling focus lost-focus


【解决方案1】:

好的,我现在明白了:

  1. Stuart 建议将QPlainTextEdit 子类化并将focusOutEvent() 函数放在那里被调用,但是:
    • e->lostFocus() 在获得和失去焦点时返回 true。
    • 我连接到该信号的插槽未被调用。
  2. 在查看我的 connect() 函数时,我注意到 Qt Creator 的自动完成功能将 const QStringList& 类型转换为 QStringList。修复了调用插槽的问题。

不知何故,在进行了一些更不相关的重新排列之后,我只是在失去焦点时发出信号,就像它应该的那样,而不是失去和获得。我不知道那是如何发生的,何时发生的。

【讨论】:

    猜你喜欢
    • 2023-03-24
    • 2011-09-16
    • 1970-01-01
    • 2011-07-24
    • 2022-09-23
    • 1970-01-01
    • 2016-04-17
    • 1970-01-01
    • 2020-01-08
    相关资源
    最近更新 更多