如何将QLineEdit的信号valueChanged连接到Qt中的自定义槽函数

13

我需要以编程的方式将QLineEdit的valueChanged信号连接到自定义槽。我知道如何使用Qt Designer进行连接,使用图形界面进行连接,但我想以编程的方式完成,这样我可以更多地了解Signals和Slots。

这是我尝试但不起作用的代码。

.cpp文件

// constructor
connect(myLineEdit, SIGNAL(valueChanged(static QString)), this, SLOT(customSlot()));

void MainWindow::customSlot()
{
    qDebug()<< "Calling Slot";
}

.h文件

private slots:
    void customSlot();

我在这里错过了什么?

谢谢

2个回答

27

QLineEdit 没有valueChanged信号,但是有textChanged信号(请参考Qt文档获取完整支持的信号列表)。

您需要更改connect()函数的调用方式。应该是:

connect(myLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(customSlot()));

如果您需要处理槽中的新文本值,可以将其定义为 customSlot(const QString &newValue) ,这样您的连接将如下所示:

connect(myLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(customSlot(const QString &)));

将valueChanged更改为textChanged和static QString更改为const QString &,然后就可以工作了。我不知道我怎么会错过这个,特别是静态QString(哇),非常感谢。还要非常感谢第二个示例,因为我也在想参数的用法。非常感谢! - fs_tigre
2
这是Qt 5的新连接方式:connect(myLineEdit, &QLineEdit::textChanged, this, &MainWindow::customSlot); - Logesh G

0

如果您有兴趣,这里也有lambda的示例:

connect(myLineEdit, &QLineEdit::textChanged, [=](QString obj) { customSlot(obj); });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接