Use object class type from GUI,

0

I'm creating a very simple program with C ++, using the IDE QT creator and I have a question

I have a Person class, with two attributes

#ifndef PERSONA_H
#define PERSONA_H
#include <iostream>
using namespace std;

class Persona
{
public:
    Persona();

    string nombre;
    int edad ;

};

#endif // PERSONA_H

In the main create a Person type object named persona1:

#include "mainwindow.h"
#include <QApplication>
#include "Persona.h"
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();


     Persona persona1;

      persona1.edad = 20;
      persona1.nombre = "Maria";


    return a.exec();
}

Create in my graphic interface a button and a label. I want that by clicking on the button, the label text changes to persona1.name, but I'm having visibility problems, and the Mainwindows class does not see the persona1 object, created in Main, my question is > how to make Mainwindows see the objects type x created in main.cpp

MainWindows code

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

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{

    ui->setupUi(this);

}

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

void MainWindow::on_pushButton_clicked()
{
    ui->label->setText(persona1.edad);  //varios errores
}
    
asked by HOLDTHEDOOR 24.09.2018 в 15:22
source

1 answer

2

Indeed, you have visibility problems. So that mainWindow can use persona1 must have, in some way, access to that object.

There are several solutions to this problem but for such a simple case I would go to the easy: Just create a function that allows to pass to MainWindow a copy of persona1 .

#include "persona.h"

class MainWindow : QMainWindow
{
  Persona persona;

public:

  void SetPersona(Persona p)
  { persona = p; }

private slots:

  void MainWindow::on_pushButton_clicked()
  {
    ui->label->setText(persona.edad);
  }
};

int main(int argc, char *argv[])
{
  Persona persona1;

  persona1.edad = 20;
  persona1.nombre = "Maria";

  QApplication a(argc, argv);
  MainWindow w;
  w.SetPersona(persona1);
  w.show();

  return a.exec();
}
    
answered by 25.09.2018 в 08:04