[solved] Modify form through main.cpp



  • hi,
    i'm sorry if my english is not good enough but i'm italian.

    I just started learning -QT- Qt and so, when i opened Qt Creator for the first time, i created a new -QT- Qt Gui Application.
    I added in the form a QPushButton, and if i build the program it runs correctly, but i don't understand how to call the QPushButton (whose name is Btest) in the main.cpp.



  • Hi,

    Welcome to the forum,

    For your question , its not a good idea to access the MainWindow(form) components in main.cpp as you can easily access ui components in your mainwindow class and do the required operations.

    But in order to access ui components in main.cpp you can try something like.

    main.cpp

    @int main(int argc, char *argv[])
    {
    QApplication app(argc, argv);

    MainWindow window;
    QList<QObject*> objectList;
    objectList = window.children();   //returns a list of child objects.
    
    foreach (QObject *obj, objectList) {
        qDebug()<<obj->objectName();
        if(obj->objectName()==QString("Btest"))
        {
            QPushButton *btn = static_cast<QPushButton*>(obj);
            //do something
        }
    }
    
    window.show();
    
    return app.exec&#40;&#41;;
    

    }@

    Other way is :

    @#include "ui_MainWindow.h"

    int main(int argc, char *argv[])
    {
    QApplication a(argc, argv);
    Ui::MainWindow window;
    window.Btest->setText("Hello World");

    //do something.......
    return a.exec();
    }@

    But I still recommend to keep the main.cpp clean.



  • I'm not quite sure what you mean by call, but

    • if you want to get a pointer to the button in <code>MainWindow</code> use <code>ui->Btest</code>
    • if you want to get a pointer to the button in <code>main</code> use <code>mainWindow.findChild<QPushButton*>("Btest")</code>
    • if you want to react on the push button beeing clicked either use <code>connect(...)</code> or create a slot called <code>on_Btest_clicked()</code>


  • Thank you, it is exactly what i was looking for :D


  • Moderators

    Glad you got the answer you needed. Please be sure and edit the original post and add [Solved] to the title! Thanks!


Log in to reply
 

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