【问题标题】:I want to use the QComboBox with an Event (Return) in QT我想在 QT 中使用带有事件(返回)的 QComboBox
【发布时间】:2021-02-14 23:49:02
【问题描述】:

我有以下问题:

我正在使用 QT 的 QComboBox 通过 Drop & Down 选择路径。 在我选择列表之一后它工作正常,路径会自动更新。但是现在如果我想通过输入路径手动编辑路径,我会立即收到警告。所以我知道这是发生争论的原因:

QComboBox::currentTextChanged

所以,如果我要更改路径,例如只更改一个字母或通过 Drop & Down 选择它“currentTextChanged”,就会调用一个新函数。 例如函数:

nextstep()

所以我想要实现的是,如果我要选择路径,则应该正常调用该函数。但是,如果我要输入新路径或手动编辑路径,我希望在输入“return”之后调用该函数。

【问题讨论】:

标签: c++ qt qcombobox


【解决方案1】:

您可以继承 QComboBox 并在您的类中定义一个新信号,该信号仅在用户输入或更改索引时发出。
为此,您必须将新信号连接到 QComboBox::lineEdit()returnPressed()editingFinished() 信号和 QComboBox::currentIndexChanged()
我选择了editingFinished(),但你也可以试试另一个。
剩下的就是将nextstep() 连接到currentTextSaved()

要在.ui 文件中使用MyComboBox,您必须将现有的QComboBoxes 提升到它。
这是官方文档:https://doc.qt.io/qt-5/designer-using-custom-widgets.html

mycombobox.h

#ifndef MYCOMBOBOX_H
#define MYCOMBOBOX_H

#include <QComboBox>

class MyComboBox : public QComboBox
{
    Q_OBJECT
public:
    MyComboBox(QWidget *parent = nullptr);

signals:
    void currentTextSaved(const QString &text);
};

#endif // MYCOMBOBOX_H

mycombobox.cpp

#include "mycombobox.h"

#include <QLineEdit>

MyComboBox::MyComboBox(QWidget *parent)
    : QComboBox(parent)
{
    connect(lineEdit(), &QLineEdit::editingFinished,
            this, [&] () { emit currentTextSaved(currentText()); });
    connect(this, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, [&] (int index) { Q_UNUSED(index) emit currentTextSaved(currentText()); });
}

这是一个例子:https://www.dropbox.com/s/sm1mszv9l2p9yqd/MyComboBox.zip?dl=0

这篇旧帖很有用https://www.qtcentre.org/threads/26860-Detecting-Enter-in-an-editable-QComboBox

【讨论】:

  • 感谢您的回答。我现在有以下问题:我无法使用您的第二条连接线。你的意思是:剩下的就是将 nextstep() 连接到 currentTextSaved()。以及如何将这些步骤与 ui 连接起来。所以实际上我正在使用以下步骤:我使用 'connect(ui.thecombbox, &QComboBox::currentTextChanged, this, &main::nextstep);.
  • @develop_96 Ops,我今天早上编辑了答案,我忘记了一篇;)
  • 通常ui 是一个指针,因此您可以在类connect(ui-&gt;myComboBox, &amp;MyComboBox::currentTextSaved, this, &amp;YourClass::yourSlot); 的构造函数或void setupUi() 方法中使用
  • 是的,我正在使用你上面所说的用户界面。但是现在如果我要使用方法 &MyComboBox::currentTextSaved 连接不起作用。
  • 感谢杰克的帮助和努力!我终于解决了:)
猜你喜欢
  • 2018-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-14
  • 1970-01-01
相关资源
最近更新 更多