c++ - 我想在 QT 中使用带有事件(返回)的 QComboBox
问题描述
我有以下问题:
我正在使用 QT 的 QComboBox 通过 Drop & Down 选择路径。在我选择列表之一后它工作正常,路径会自动更新。但是现在如果我想通过输入路径手动编辑路径,我会立即收到警告。所以我知道这是争论的原因:
QComboBox::currentTextChanged
因此,如果我要更改路径,例如仅更改一个字母或通过 Drop & Down 选择它,“currentTextChanged”将调用一个新函数。例如函数:
nextstep()
所以我想要实现的是,如果我要选择一条路径,则应该正常调用该函数。但是,如果我要输入新路径或手动编辑路径,我希望在输入“return”之后调用该函数。
解决方案
您可以继承 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
推荐阅读
- spring-mvc - Struts 1.2.9 到 Spring MVC 迁移 - ActionForms 的处理范围
- recursion - 动态内存分配查询
- jboss - 从 MRI 控制台接收图像的问题
- python - 如何从 Keras.layers 实现 Merge
- google-apps-script - Google Script 在单元格为黑色的 1 列中插入公式
- apache-spark - pyspark中两个时间戳之间的运行总和
- c# - 运算符“||” 不能应用于 aspx 页面上的“布尔”和“字符串”类型的操作数
- javascript - 显示更多/更少切换不会显示所有内容
- android - 关闭应用程序时异步任务不起作用
- json - 服务器端排序的数据未在数据表中以相同的顺序显示