Qt不能从lineedit中获取文本

Qt not getting text from lineedit

本文关键字:获取 取文本 lineedit 不能 Qt      更新时间:2023-10-16
QString username = ui->lineEdit->text();
QString password = ui->lineEdit_2->text();
QMessageBox Failed;
Failed.setWindowFlags(Qt::FramelessWindowHint);
if(username == "Jon" && password == "12345")
{
    Failed.setText("Login failed. Try again.");
    Failed.exec();
} else {
    Failed.setText(password);
    Failed.exec();
}

使用qt。抱歉,如果这个问题之前已经被问到,我是相当新的,无法找到一个答案。我不明白我做错了什么。我将用户名和密码设置为ui上行编辑中的文本。但是每次我点击这个按钮功能,对话框文本的输出总是空白的。我怎样才能使文本被读取?

好的,我运行了一些测试,这是我发现得到的:

如果你设置了某种类型的信号槽连接,调用了一个包含if/else语句的函数,程序将会工作。下面是我编写的程序:

dialog.h:

    #ifndef DIALOG_H
    #define DIALOG_H
    #include "ui_dialog.h"
    #include <QDialog>
    class DialogClass :  public QDialog, public Ui::Dialog
    {
        Q_OBJECT
    public:
        DialogClass(QWidget *parent = 0);
    public slots:
        void check();
    };
    #endif // DIALOG_H

Dialog.cpp:

    #include "dialog.h"
    #include <QMessageBox>
    DialogClass::DialogClass(QWidget *parent) : QDialog(parent)
    {
        setupUi(this);
        connect(pushButton, SIGNAL(clicked()), this, SLOT(check()));
    }
    void DialogClass::check()
    {
        QString username = lineEdit->text();
        QString password = lineEdit_2->text();
        QMessageBox Failed;
        Failed.setWindowFlags(Qt::FramelessWindowHint);
        if(username == "Jon" && password == "12345")
        {
            Failed.setText("Login failed. Try again.");
            Failed.exec();
        } else {
            Failed.setText(password);
            Failed.exec();
        }
    }

和main.cpp

    #include <QApplication>
    #include <QMessageBox>
    #include "dialog.h"
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        DialogClass w;
        w.show();
        return a.exec();
    }
基本上,我所做的就是使一个对话框类很像你的main函数,只是我的有一个按钮对话框。UI有一个按钮。之后,我使用该按钮来建立一个信号槽连接,以确保当单击该按钮时,它将调用check()函数(这基本上是您的if/else算法进入一个槽),该函数检查用户名是否为"Jon",密码是否为"12345"。

为什么你最初的实现不能工作?

对不起,我不能肯定。

然而,这种方法应该是有效的。如果我弄清楚为什么if语句没有出现,我将添加到答案中。但是,这种方法应该可以使您的应用程序正常工作。

编码快乐!