c++ - 单击按钮时 QT 消息框不弹出

标签 c++ qt qt5

我刚刚开始学习QT,我想要完成的是在单击按钮时获取弹出消息。 我的文件如下所示:

ma​​in.cpp

#include "mainwindow.h"
#include <QApplication>
#include <QDialog>
#include <QLabel>
#include <QMessageBox>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QWidget>


int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    MainWindow *mainWindow = new MainWindow();


    QLabel *text = new QLabel("Some text");
    QPushButton *btn = new QPushButton("Click");

    QHBoxLayout *layout = new QHBoxLayout;

    layout->addWidget(btn);
    layout->addWidget(text);

    QObject::connect(btn, SIGNAL(clicked()), &app, SLOT(popup()));

    mainWindow->setLayout(layout);
    mainWindow->show();

    return app.exec();
}

ma​​inwindow.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;
}

void MainWindow::popUp()
{
    QMessageBox::information(this, "New Box", "Message");
}

ma​​inwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QMessageBox>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();


private slots:
    void popUp();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

您能否解释一下我做错了什么,或者我的代码中可能缺少某些内容。

最佳答案

我建议图形部分在类 MainWindow 中实现它,因为私有(private)成员 ui 负责处理设计。

#include <QMessageBox>
#include <QLabel>
#include <QLayout>
#include <QPushButton>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QLabel *text = new QLabel("Some text");
    QPushButton *btn = new QPushButton("Click");

    QHBoxLayout *layout = new QHBoxLayout;

    layout->addWidget(btn);
    layout->addWidget(text);

    ui->centralWidget->setLayout(layout);

    connect(btn, &QPushButton::clicked, this, &MainWindow::popUp);
}

不要对 main.cpp 进行任何更改,代码应如下所示:

#include "mainwindow.h"
#include <QApplication>



int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;

    w.show();

    return a.exec();
}

关于c++ - 单击按钮时 QT 消息框不弹出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43502297/

相关文章:

c++ - 在 C++ (C) 中使用全局范围对象(结构)是否可以?

c++ - 运算符/重载

android - 如何防止 Android 设备从 Qt 应用程序进入休眠状态

qt - 计算QPainterPath的填充区域

javascript - Golang中如何使用javascript获取特定网站元素或提交表单

qt - Flickable 内的 MouseArea 阻止它轻弹

qt5 - Qt 是在没有 ICU 支持的情况下构建的,WebKit 被禁用。 VS2012

Python - 导入 C++ 模块接口(interface) - 无法打开共享对象文件

c++ - 是否有其他类型的 void_t 的标准概括?

c++ - 将私有(private)子类添加到 Q_DECLARE_METATYPE