【发布时间】:2018-11-30 17:05:10
【问题描述】:
我有一个函数(公共槽)
void Parts::Testing(QString text)
{
ui_add_new_part->lineEdit_InvoiceNumber->setText(text);
}
连接到 QCompleter 的信号为
connect(completer_part_invoice, SIGNAL(activated(QString)),
this, SLOT(Testing(QString)));
上述代码的目的是,每当我使用 QCompleter 中的 complete() 函数时,建议会在行编辑中弹出,并且在单击建议时,该特定文本应该出现在行编辑中。
上面的代码按我的预期工作
问题 由于该函数只有一个语句,我想在连接函数本身中使用 lambda 表达式。从而节省代码长度并提高可读性。 谷歌搜索后,我找到了this。在引用该网站后,我编写了这样的代码
试试 1
connect(
completer_part_invoice, &QCompleter::activated,
[&]( const QString &text )
{
ui_add_new_part->lineEdit_InvoiceNumber->setText(text);
});
但是 Qt 抛出错误
error: no matching function for call to 'Parts::connect(QCompleter*&, <unresolved overloaded function type>, Parts::pop_Up_Invoices()::<lambda(const QString&)>)'
);
^
试试 2
connect(
completer_part_invoice, SIGNAL(activated(QString)),
[&]( const QString &text )
{
ui_add_new_part->lineEdit_InvoiceNumber->setText(text);
});
但是 Qt 抛出错误
error: no matching function for call to 'Parts::connect(QCompleter*&, const char [20], Parts::pop_Up_Invoices()::<lambda(const QString&)>)'
});
^
我做错了什么?
Try3
正如我在 cmets 中指出的那样,我也尝试过
connect(
completer_part_invoice, QOverload<const QString &>(&QCompleter::activated),
[&](const QString &text)->void
{
ui_add_new_part->lineEdit_InvoiceNumber->setText(text);
});
我遇到的错误
error: no matching function for call to 'QOverload<const QString&>::QOverload(<unresolved overloaded function type>)'
completer_part_invoice, QOverload<const QString &>(&QCompleter::activated),
^
【问题讨论】:
-
你应该添加
this作为你的 lambda-slot 的接收者,因为否则信号可能会执行 lambda 并且即使你的对象已经被销毁,也尝试访问ui_add_new_part,这是一个很好的选择练习。 -
@G.M.我尝试了他们所有可能的解决方案,但没有帮助
-
@ymoreau 我试过 [this, &] 以及 [&, this] 也试过 [this] 但也没有帮助
-
@king_nak 答案与 G.M 首次指出的解决方案几乎相同
-
1.它是
QOverload<T>::of(...)或qOverload<T>(...)。 2. 你用什么Qt版本? 3.你用什么编译器&版本/C++版本?