0

In my MainWindow i have a combobox and a select button. When the select button is clicked a new window is opened.

I want to be able to create a QString variable on the MainWindow that contains the text from the combobox, and pass that QString to the new window. The new window is going to perform different tasks, based on the contents of the QString (based on the selection of the combobox).

The following is my code so far...

#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();

}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Dave
  • 3
  • 1
  • 1
    Can you alter `TestWindow`'s code? Simplest way is adding an parameter to `TestWindow.Show()` or its constructor. Also using enum class rather than string is suggested. – Louis Go Jul 27 '20 at 01:42
  • Does this answer your question? [How to access QString value from one class (window UI) in another class?](https://stackoverflow.com/questions/53316749/how-to-access-qstring-value-from-one-class-window-ui-in-another-class) – scopchanov Jul 27 '20 at 07:38

1 Answers1

0

The simplest way to do this is, as suggested in the comments, to pass the variable as parameter in the constructor of the class Testwindow. Then you can save the value of the string in a private variable in your Testwindow class and do whatever you want with it.

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
}

mainwindow.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();

}
Erel
  • 512
  • 1
  • 5
  • 14
Salvo
  • 286
  • 2
  • 20