簡體   English   中英

Qt GUI C++:使用 GUI 輸入值,然后完全關閉 GUI 並使用輸入變量繼續 C++ 主代碼

[英]Qt GUI C++: Input values using GUI, then close GUI entirely and continue with main C++ code using inputed variables

所以我正在學習 C++ 的 Qt GUI(Linux Mint 21、Qt Creator 5)。 我正在嘗試編寫一個簡單的程序,它將打開一個包含 3 個字段的框,供用戶輸入值:a1、a2 和 a3。 然后有兩個按鈕: OKQuit 有關 GUI 框,請參見下面的屏幕截圖。 然后,當用戶點擊“退出”時,GUI 和整個 C++ 代碼應該終止。 我讓這部分工作了。 當用戶點擊“確定”時,Qt GUI 應將這些值保存到變量中,完全退出 GUI,並將變量傳遞回主要的 c++ 代碼以供使用......這就是我被卡住的地方:

Qt GUI輸入框

我希望 Qt GUI 完全關閉並使用用戶輸入的值/變量將控制權傳回主 c++。 這就是我被困的地方。 代碼如下:

主.cpp:

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


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

    // Qt GUI stops, main C++ code continues....
    //=========================================================

    //float a1_temp = MainWindow::on_pushButton_clicked();
    //float a2_temp = MainWindow::on_pushButton_clicked();
    //float a3_temp = MainWindow::on_pushButton_clicked();

    //std::cout << "Qt passed back into main: " << a1_temp << std::endl;
    //std::cout << "Qt passed back into main: " << a2_temp << std::endl;
    //std::cout << "Qt passed back into main: " << a3_temp << std::endl;

}

主窗口.cpp:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <iostream>

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

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_2_clicked() // When QUIT is pressed, exit/terminate the whole program
{
    QApplication::quit();
}

void MainWindow::on_pushButton_clicked() // When OK is pressed, save values and return to main C++
{
    float a1 = ui->lineEdit->text().toFloat();
    float a2 = ui->lineEdit_2->text().toFloat();
    float a3 = ui->lineEdit_3->text().toFloat();

    // print values to verify of variables correctly saved the values
    std::cout << a1 << std::endl;
    std::cout << a2 << std::endl;
    std::cout << a3 << std::endl;

}

主窗口.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_pushButton_2_clicked();

    void on_pushButton_clicked();

private:
    Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H

看起來你唯一的問題是當exec()返回時你從main()調用return

return a.exec();

您可以將其替換為:

int retVal = a.exec();

[.... Main C++ code continues here ....]

float a1 = w.ui->lineEdit->text().toFloat();
[...]

return retVal;  // only at the end of main()

...並獲得您想要的行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM