[solved] Modify form through main.cpp
-
wrote on 11 Jul 2012, 21:01 last edited by
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. -
wrote on 12 Jul 2012, 05:10 last edited by
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();
}@
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.
-
wrote on 12 Jul 2012, 06:32 last edited by
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>
-
wrote on 12 Jul 2012, 07:39 last edited by
Thank you, it is exactly what i was looking for :D
-
wrote on 12 Jul 2012, 13:32 last edited by
Glad you got the answer you needed. Please be sure and edit the original post and add [Solved] to the title! Thanks!
1/5