user3053231
user3053231

Reputation:

Change object of other class qt

I am using Qt and C++, after click on menu item second window appears, and after click on a button in second menu (slot saveData()), I want to change object (obj_map) of class MainMenu. Is it possible, and how to do it the best way? Because I now cannot modify obj_map, because it is in different class. I tried to do something with pointers, but the result was a segmentation fault.

Main Window:

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    map obj_map;

public Q_SLOTS:
    void saveMap();

private:
    Ui::MainWindow *ui;
};

Other window which appears after click in on menu item in main window.

namespace Ui
{
    class PreferencesWindow;
}

class PreferencesWindow : public QWidget
{
    Q_OBJECT
public:
    explicit PreferencesWindow(QWidget *parent = 0);
public Q_SLOTS:
    void saveData();
private:
    Ui::PreferencesWindow *uip;
};

From here I need to change obj_map

void PreferencesWindow::saveData()
{
     // FROM HERE I NEED TO CHANGE obj_map
}

Preferences object is created in a slot:

void MainWindow::saveMap()
{
    PreferencesWindow *p = new PreferencesWindow();
    p->show();
}

Upvotes: 0

Views: 734

Answers (2)

Michael
Michael

Reputation: 1035

You could use signals and slots: when saveData() is called, emit a signal, like emit saveDataClicked() and catch that signal in the MainWindow with a slot called change_obj_map. There, you can do your changes. So, in MainWindow you can write:

connect (PreferencesWindow, SIGNAL(saveDataClicked()), this, SLOT(change_obj_map());

and then in the slot:

void change_obj_map()
{
  // Do your changes here
}

Another way is having a local obj_map in PreferencesWindow that is a pointer to the address of obj_map in MainWindow. So, when you create PreferencesWindow, you can just pass the address of MainWindow's obj_map to the constructor and assign that address to the local variable obj_map.

Upvotes: 3

jpo38
jpo38

Reputation: 21514

As PreferencesWindow objects are created by MainWindow, the easiest is to have PreferencesWindow objects store a pointer to MainWindow:

class MainWindow;
class PreferencesWindow : public QWidget
{
    Q_OBJECT
public:
    explicit PreferencesWindow(MainWindow *parent = 0);
public Q_SLOTS:
    void saveData();
private:
    Ui::PreferencesWindow *uip;
    MainWindow* m_mainwindow;
};

Pass the pointer upon construction:

void MainWindow::saveMap()
{
    PreferencesWindow *p = new PreferencesWindow( this );
    p->show();
}

Then use it:

PreferencesWindow::PreferencesWindow(MainWindow *parent) : 
    QWidget( parent ),
    m_mainwindow( parent )
{

}

void PreferencesWindow::saveData()
{
    // FROM HERE I NEED TO CHANGE obj_map
    m_mainwindow->obj_map.....it's accessible!
}

Upvotes: 1

Related Questions