Reputation: 23
My GUI class in constructor is creating new object of my database class. It looks like that:
GUI::GUI(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
Baza *plik = new Baza();
connect(ui.insertBtn, &QPushButton::clicked, this, &GUI::run);
}
I've managed to get user input from QDialog:
void GUI::run() {
DialogInput dialog;
dialog.exec();
site_text = dialog.getSite();
}
How should I pass site_text
to function in Baza
class? I need to use that object (plik) created in GUI constructor but I can't access it from GUI::run()
function.
Upvotes: 2
Views: 624
Reputation: 99
When you create a pointer inside the constructor the scope of the object is till the end of the constructor.
You need to create a global private variable to GUI class for that variable to be accessed by all the method in the same class. Baza * pLink;
When you create a pointer in the constructor, do not forget to delete the same pointer in the Destruction.
class GUI : public QWidget{
//...
GUI();
~GUI();
private:
Baza * pLink;
}
GUI::GUI(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
pLink = new Baza();
connect(ui.insertBtn, &QPushButton::clicked, this, &GUI::run);
}
GUI::~GUI()
{
delete pLink;
}
void GUI::run() {
DialogInput dialog;
dialog.exec();
site_text = dialog.getSite();
/* use the pointer to call the method to pass site_text */
pLink->SomeMethod(site_text);
}
Naming convention would play a big role when you are declaring local variables for the function and the global variables for the class.
So use pLink
or consider using m_pLink
where m_
would be added to all the global variable and p
for pointer type.
Upvotes: 0
Reputation:
Add plik
to the declaration of GUI
:
class GUI : public QWidget {
// ...
Baza* plik;
};
then in the constructor
GUI::GUI(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
plik = new Baza();
connect(ui.insertBtn, &QPushButton::clicked, this, &GUI::run);
}
As your code stands, plik
is leaked as soon as GUI constructor completes.
Clean up plik
in the destructor:
GUI::~GUI()
{
// ...
delete plik;
}
Alternatively, use std::unique_ptr
to store plik
in GUI
so you don't need to remember to destruct it. Or, if plik
benefits from deriving from QObject
(e.g. for signals and slots), you can parent it to the GUI
and Qt will handle the destruction. In both cases, this advice assumes plik
has the same lifetime as GUI
.
Upvotes: 5