首页 > 解决方案 > 我想在 QT 中使用带有事件(返回)的 QComboBox

问题描述

我有以下问题:

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

QComboBox::currentTextChanged

因此,如果我要更改路径,例如仅更改一个字母或通过 Drop & Down 选择它,“currentTextChanged”将调用一个新函数。例如函数:

nextstep()

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

标签: c++qtqcombobox

解决方案


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

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

我的组合框

#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

我的组合框.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


推荐阅读