1

我对 QT 完全陌生,我想准备一个窗口并从用户那里获取一些输入,然后使用此输入运行一个控制台并在控制台中显示输出。我曾尝试在 exec 之后编写代码,但似乎不可能:

int main(int argc, char *argv[])
{
    int retmain = 0;
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    cout<<"pos500"<<endl;
    retmain = a.exec();
    cout<<"pos50"<<endl;
//doing something

    return retmain;
}

我不知道为什么,但是在 a.exec(); 之后 什么都没发生。所以我在互联网上搜索并在stackoverflow中找到了以下主题: 显示窗口后如何调用函数?

但我想结束图形窗口,然后做我的过程。

4

1 回答 1

1

你需要打电话QCoreApplication::exit()exec你返回控制权。

调用此函数后,应用程序离开主事件循环并从对 exec() 的调用中返回。exec() 函数返回 returnCode。如果事件循环没有运行,这个函数什么也不做。

一个简单的例子是:

//mainwindow.h
//////////////////////////////////////////////////
#pragma once
#include <QtWidgets/QMainWindow>
#include <QtCore/QCoreApplication>

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    MainWindow(QWidget *parent = 0);
    void closeEvent(QCloseEvent *event);
    ~MainWindow();
};

//mainwindow.cpp
//////////////////////////////////////////////////
#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
}
void MainWindow::closeEvent(QCloseEvent *event)
{
    QCoreApplication::exit(0);
    QMainWindow::closeEvent(event);
}
MainWindow::~MainWindow(){}

//main.cpp
//////////////////////////////////////////////////
#include "mainwindow.h"
#include <QApplication>

#include <iostream>

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

    a.exec();
    std::cout << "test" << std::endl;
    return 0;
}
于 2019-05-10T11:23:50.567 回答