[英]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。 然后有两个按钮: OK和Quit 。 有关 GUI 框,请参见下面的屏幕截图。 然后,当用户点击“退出”时,GUI 和整个 C++ 代码应该终止。 我让这部分工作了。 当用户点击“确定”时,Qt GUI 应将这些值保存到变量中,完全退出 GUI,并将变量传递回主要的 c++ 代码以供使用......这就是我被卡住的地方:
我希望 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.