July 11, 2012

Twentyone Twentyone
Lab Rat
3 posts

[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.

4 replies

July 12, 2012

Sam Sam
Area 51 Engineer
623 posts

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

  1. int main(int argc, char *argv[])
  2. {
  3.     QApplication app(argc, argv);
  4.    
  5.     MainWindow window;
  6.     QList<QObject*> objectList;
  7.     objectList = window.children();   //returns a list of child objects.
  8.  
  9.     foreach (QObject *obj, objectList) {
  10.         qDebug()<<obj->objectName();
  11.         if(obj->objectName()==QString("Btest"))
  12.         {
  13.             QPushButton *btn = static_cast<QPushButton*>(obj);
  14.             //do something
  15.         }
  16.     }
  17.  
  18.     window.show();
  19.  
  20.     return app.exec();
  21. }

Other way is :

  1. #include "ui_MainWindow.h"
  2.  
  3. int main(int argc, char *argv[])
  4. {
  5.     QApplication a(argc, argv);
  6.     Ui::MainWindow window;
  7.     window.Btest->setText("Hello World");
  8.  
  9. //do something.......
  10.     return a.exec();
  11. }

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

July 12, 2012

Lukas Geyer Lukas Geyer
Dinosaur Breeder
2074 posts

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

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

July 12, 2012

Twentyone Twentyone
Lab Rat
3 posts

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

July 12, 2012

mlong mlong
Mad Scientist
1517 posts

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

 Signature 

Senior Software Engineer
AccuWeather Enterprise Solutions
/* My views and opinions do not necessarily reflect those of my employer.  Void where prohibited. */

 
  ‹‹ QSlider problem on OS X - bug in Qt?      Handling mouseevent in Qstatusbar . ››

You must log in to post a reply. Not a member yet? Register here!