【问题标题】:Passing a variable from MainWindow to new window将变量从 MainWindow 传递到新窗口
【发布时间】:2020-07-27 01:17:17
【问题描述】:

在我的 MainWindow 中,我有一个组合框和一个选择按钮。单击选择按钮时会打开一个新窗口。

我希望能够在包含组合框文本的 MainWindow 上创建一个 QString 变量,并将该 QString 传递给新窗口。新窗口将根据 QString 的内容(基于组合框的选择)执行不同的任务。

以下是我目前的代码...

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "testwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->cmboTestSelect->addItem("{Please Select a Test}");
    ui->cmboTestSelect->addItem("Test 1");
    ui->cmboTestSelect->addItem("Test 2");
    ui->cmboTestSelect->addItem("Test 3");
    ui->cmboTestSelect->addItem("Test 4");
}

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


void MainWindow::on_btnTestSelect_clicked()
{
    QString str_TestSelect = ui->cmboTestSelect->currentText(); //stores "Test Name" in string
    hide();
    Testwindow = new testwindow(this);
    Testwindow->show();

}

【问题讨论】:

标签: c++ qt user-interface


【解决方案1】:

按照 cmets 中的建议,最简单的方法是在类 Testwindow 的构造函数中将变量作为参数传递。然后,您可以将字符串的值保存在 Testwindow 类中的私有变量中,然后对它做任何您想做的事情。

testwindow.h

class Testwindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit Testwindow(QString text, QWidget *parent = nullptr);

signals:
    
private:
    QString comboBoxText;

};

testwindow.cpp

Testwindow::Testwindow(QString text, QWidget *parent) : QMainWindow(parent)
{
    comboBoxText = text;    //now you can use comboBoxText in the rest of Testwindow class
}

主窗口.cpp

void MainWindow::on_btnTestSelect_clicked()
{
    QString str_TestSelect = ui->cmboTestSelect->currentText(); //stores "Test Name" in string
    hide();
    Testwindow *w = new Testwindow(str_TestSelect, this);
    w->show();

}

【讨论】:

  • 这回答了我的问题。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多