Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

I would like to use searchString in Dialog.



  • I always get empty string in the following codes.
    Could you modift my codes to get searchStirng ?

    //mainwindow.cpp
    
    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QDialog>
    #include <QLineEdit>
    #include <QPushButton>
    #include <QVBoxLayout>
    #include <QMessageBox>
    
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        QDialog *Dialog = new QDialog;
        QVBoxLayout  *Layout = new QVBoxLayout();
        QLineEdit *line = new QLineEdit;
        QPushButton *button = new QPushButton(tr("Find"));
        Layout->addWidget(line);
        Layout->addWidget(button);
        Dialog->setLayout(Layout);
    
        Dialog->exec();
        searchString = line->text();
    
        connect(button, SIGNAL(clicked()), this, SLOT(find()));
    
    }
    
    MainWindow::~MainWindow()
    {
        delete ui;
    }
    
    void MainWindow::find()
    {
       QMessageBox msgBox;
       msgBox.setText(tr("Find String : ") + searchString);
       msgBox.exec();
    }
    
    //mainwindow.h
    
    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    
    #include <QMainWindow>
    
    namespace Ui {
    class MainWindow;
    }
    
    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    
    public:
        explicit MainWindow(QWidget *parent = nullptr);
        ~MainWindow();
    
    private slots:
        void find();
    
    private:
        Ui::MainWindow *ui;
        QString searchString;
    };
    
    #endif // MAINWINDOW_H
    
    

  • Lifetime Qt Champion

    Hi
    You take the text in the constructor
    searchString = line->text();
    and at that point, nothing is likely typed into it.

    I think you want something more like

    void MainWindow::find()
    {
       QMessageBox msgBox;
       msgBox.setText(tr("Find String : ") +  line->text());
       msgBox.exec();
    }
    

    so it takes the newest text.
    could also be

       searchString = line->text();
       QMessageBox msgBox;
       msgBox.setText(tr("Find String : ") + searchString);
       msgBox.exec();
    


  • @mrjj

    Thank you for your reply.
    I get error message . "I get use of undeclared identifier 'line'. "


  • Lifetime Qt Champion

    Hi,

    Because you declared line in your constructor. Make it a member variable of your class. However, since you are using Designer, why not use it to add that QLineEdit to your UI ?



  • @SGaist

    Thank you for your help.


Log in to reply