【发布时间】:2012-10-07 08:40:07
【问题描述】:
主窗口.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
主窗口.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();
}
上面给出了所有代码。在一般的 Qt GUI 程序中,我在 UI 窗体上放置了一个 pushButton,并尝试在 main.cpp 中使用它。但出现以下错误:
main.cpp:10: Error:'pushButton' was not declared in this scope
你能给我一个解决方案吗?如何在 main.cpp 中调用它? 谢谢!
补充1:
主窗口.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;
}
如果我这样做,那么程序可以运行但不能关闭整个应用程序。我猜这是因为 QCoreApplication::instance() 由于在构造函数阶段 QApplication 不存在而返回 null,对吧?
互补2:
主窗口.cpp
void MainWindow::on_pushButton_clicked()
{
close();
}
一种解决方案是在 mainwindow.cpp 中添加新的 pushButton 插槽,如上所示。 但是我仍然希望知道如何按照我的方式去做(这篇文章的主要部分)?
补充3:
Alberto 的代码通过使用 QWidget 可以正常工作,如下所示。
ui->setupUi(this);
connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(close()));
【问题讨论】:
-
为什么需要在 main.cpp 中如此糟糕地调用它?
-
那该怎么办呢?我需要退出整个应用程序,但是指向整个应用程序的'a'在main.cpp中,所以我把代码放在里面。
-
您始终可以通过在代码中的任何位置调用静态 QCoreApplication::instance() 函数来检索指向当前 Q(Core)Application 的指针。
-
感谢您的回答!请检查我上面的主要帖子,补充部分。
-
为什么要连接到“关闭”的 SLOT? QCoreApp 没有。您正在寻找的是“退出”SLOT。 (ref)
标签: qt