我想在 QT 中使用带有事件 (Return) 的 QComboBox

I want to use the QComboBox with an Event (Return) in QT

我遇到以下问题:

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

QComboBox::currentTextChanged

因此,如果我要更改路径,例如仅更改一个字母或 select 通过下拉“currentTextChanged”,则会调用一个新函数。 例如函数:

nextstep()

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

您可以子class QComboBox 并在您的 class 中定义一个新信号,该信号仅在用户键入 enter 或索引更改时发出。
为此,您必须将新信号连接到 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

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