[英]How to connect LineEdit and PushButton in Qt?
我使用Qt Designer創建了一個.ui文件,並在該文件中創建了一個最初被禁用的PushButton
,我還具有LineEdit
。 我想連接LineEdit
和PushBotton
以便在LineEdit
更改文本時,將啟用PushButton
,但是在Signals和slot中找不到任何這樣的選項。 有人可以幫忙嗎?
您必須編寫一個自定義插槽(非常簡單)。
將此添加到您的MainWindow聲明( .h文件):
private slots:
void checkInput(const QString &text);
您的.cpp文件:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->lineEdit, SIGNAL(textChanged(QString)), this, SLOT(checkInput(QString)));
}
void MainWindow::checkInput(const QString &text)
{
ui->pushButton->setEnabled(!text.isEmpty());
}
要將此插槽添加到Qt Designer,請執行以下操作:
在Qt 5中,通常不需要瑣碎的專用插槽,而應使用lambda代替:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->lineEdit, &QLineEdit::textChanged, [this](const QString & text) {
ui->pushButton->setEnabled(!text.isEmpty());
});
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.