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 = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
main.cpp
#include <QtGui/QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
QObject::connect(pushButton, SIGNAL(clicked()),
&a, SLOT(quit()));
return a.exec();
}
All the codes are given above. In a general Qt GUI program, I put a pushButton on the UI Form and tried to use it in main.cpp. But below error was given:
main.cpp:10: Error:'pushButton' was not declared in this scope
Could you please give me a solution? How can I call it in main.cpp? Thanks!
Complement1:
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QObject::connect(ui->pushButton, SIGNAL(clicked()),
QCoreApplication::instance(), SLOT(close()));
}
MainWindow::~MainWindow()
{
delete ui;
}
If I do it this way, then the program can run but cannot close the whole application. I guess that is because the QCoreApplication::instance() returns null due to in the constructor phase the QApplication doesn't exist, right?
Complement2:
mainwindow.cpp
void MainWindow::on_pushButton_clicked()
{
close();
}
One solution is to add new slot of the pushButton in mainwindow.cpp, like above. But still I hope to know how to do it my way (main part of this post)?
Complement3:
Alberto's code works fine by using QWidget as below way.
ui->setupUi(this);
connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(close()));