问题描述:

I have a pushbutton on my main form named pushButton_Tar1ex, it has some text on it. I have another pushbutton on my main form named pushButton_RenameTargets.

When I push pushButton_RenameTargets, the following code executes:

void MainWindow::on_pushButton_RenameTargets_clicked()

{

RenameTargets renametargets;

renametargets.target1NameCurrent = ui->pushButton_Tar1ex->text();

renametargets.setModal(true);

renametargets.exec();

}

So my second window is called RenameTargets and the first line of code in the function creates an object renametargets. Then I set renametargets.target1NameCurrent = ui->pushButton_Tar1ex->text();which target1NameCurrent is in the public: portion of renametargets.h. Then in RenameTargets I set the label to the pushbuttontext by:

RenameTargets::RenameTargets(QWidget *parent) :

QDialog(parent),

ui(new Ui::RenameTargets)

{

ui->setupUi(this);

ui->label_currentNameTarget1->setText(target1NameCurrent);

}

Yet nothing appears in the label label_currentNameTarget1.

I have run some qDebug stuff and what happens is when RenameTargets renametargets; is run when I push the button it runs through the RenameTargets ui(new Ui::RenameTargets) part before the renametargets.target1NameCurrent = ui->pushButton_Tar1ex->text(); is declared.

What am I doing wrong? any help would be appreciated.

网友答案:

you set renametargets.target1NameCurrent member variable after constructing your object renametargets... that's the problem, since you use target1NameCurrent in your constructor to set your label.

One solution is to pass target1NameCurrent through the constructor.

void MainWindow::on_pushButton_RenameTargets_clicked()
{
  RenameTargets renametargets(this, ui->pushButton_Tar1ex->text());
  renametargets.setModal(true);
  renametargets.exec();
}

RenameTargets.cpp

RenameTargets::RenameTargets(QWidget *parent, const QString & target1NameCurrent):
    QDialog(parent),
    ui(new Ui::RenameTargets),
    target1NameCurrent(target1NameCurrent)
{
  ui->setupUi(this);
  ui->label_currentNameTarget1->setText(target1NameCurrent);

}

RenameTargets.h

class RenameTargets{
  public:
    RenameTargets(QWidget *parent, const QString & target1NameCurrent);

};

Also, you can just initialize label_currentNameTarget1 in another function in RenameTargets after constructing renametargets and initializing renametargets.target1NameCurrent.

相关阅读:
Top