Sending QString value from one form class to another



  • I have declared a QString in mainwindow.h as

    public : QString str;

    I have used the str inside a method of mainwindow.cpp and it now has a string value. I have another form named dialog.cpp I want to display the contents of str in a label named label1 in dialog.cpp!

    Even though i imported mainwindow.h and mainwindow.cpp to dialog.cpp and used the following code to print the contents of str!

    ui->label->setText(str);

    It returns the error str as an undecalred identifier! How can i correct this?



  • HI,

    have u declared str in dialog.cpp where u can show values to label,
    and can u post the code of how u made a string value avialable in dialog.cpp from mainwindow.cpp.

    Thanks,


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Based on your question, you seem to be new to C++. I highly recommend that you start by reading a good book on the subject and then follow Qt's tutorial and examples.

    Also, there are already a lot of similar questions on this forum. Did you try to search it first ?



  • @Pradeep-Kumar

    Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
    {
    ui->setupUi(this);
    MainWindow m;

    ui->label->setText(str);
    

    }



  • Hi,

    u have not declared str, so the reason getting error.

    Thanks,


  • Qt Champions 2016

    @Kasun
    Hi, you create another instance of mainwindow.
    Not sure that is what you want..
    anyway, since str is inside the class, you must do

    MainWindow m;
    ui->label->setText(m.str);

    But the m is not the running mainwindow. Its a new one.



  • @mrjj I need from the old window! How can I do it?


  • Qt Champions 2016

    @Kasun

    Often its easy to share from mainwindow since it opens the dialog

    So if you add function to set the text to dialog.
    public:
    void Dialog::SetMyText(QString text) {
    ui->label->setText(text);
    }

    Then in mainwin where u show dialog
    void Mainwindow::ShowDia() {
    Dialog dia;
    dia.setMyText(str);
    dia.exec();
    }



  • you can send the string to other class by simply placing it in the Signal, and catch the signal at the other class.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.