如何将信号值Changed从QLineEdit连接到Qt中的自定义插槽

How to connect the signal valueChanged from QLineEdit to a custom slot in Qt

本文关键字:Qt 插槽 自定义 连接 QLineEdit 信号 Changed      更新时间:2023-10-16

我需要用程序将QLineEdit的valueChanged信号连接到自定义插槽。我知道如何使用Qt Designer进行连接,并使用图形界面进行连接,但我想以编程方式进行连接,这样我就可以了解更多关于信号和插槽的信息。

这就是我所拥有的不起作用的东西。

.cpp文件

// constructor
connect(myLineEdit, SIGNAL(valueChanged(static QString)), this, SLOT(customSlot()));
void MainWindow::customSlot()
{
    qDebug()<< "Calling Slot";
}

.h文件

private slots:
    void customSlot();

我在这里错过了什么?

感谢

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 &)));

如果感兴趣,这里还有lambda:

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