Access method from class object in another class
-
Hi
I assume you are also just starting with c++ so here is a sample
showing the wise words of @Rednemus as code
https://www.dropbox.com/s/punlkkwekxeflgl/myotherclass.zip?dl=0
It has button and when clicked it calls a function in another class.Note, calling a function directly from another class makes them
really know each other. ( which is (often) bad , later on as changes affect more classes)
A (often) better way is to use Signals and slots.
http://doc.qt.io/qt-5/signalsandslots.html -
Yep i'm starting with c++. As I didn't get to clear cut solution. I'll explain my problem in a more detailed manner.
I have stacked widget in class Top(derived from QWidget).
I have a Page class with object is created in Top and added to stacked widget.
And i have a class Keyboard which has a line edit and a button.
Page class also has line edit.Now i need to get text from Keyboard line edit when i press a button and pass it(copy) to Page line edit( it could just be QString passing when pressing a button for the sake of simplicity).
My first attempt was to make object of Keyboard in Top and add it to stacked widget. That's where my initial problem occurred there was no way to pass or call anything from Keyboard to Page or vice-versa as VRonin pointed it out.
For my second attempt i added object of Keyboard in Page and i now can access line edit text from Page easily by pressing a button(call method of Keyboard to get text).
But I want to get line edit text of Keyboard when i press button in Keyboard! and copy it to Page line edit.
project -
add a signal in Keyboard
void puttonPressed(const QString& val);
then in Keyboard constructor put:
connect(button,&QPushButton::clicked,[this]()->void{puttonPressed(lineEdit->text());});
now in Page add a slot:
void setLineEdit(const QString& val){ lineEdit->setText(val); }
finally in Top constructor, after you create Page and Keyboard, call
connect(keyboard,&Keyboard::puttonPressed,page,&Page::setLineEdit);
-
Hi,
Create the objects of Class C and Class B in Class A.
Later for the access of functions(), use can use signal and slot communication.
If u want Class C to communicate with Class B.Ex :
Class A
{
B objectB;
C objectC;// As you have created the object in this class. use connect statement, connect(objectC,SIGNAL(signalName),this,SLOT(slotName)));
public slots:
void slotName();void slotName()
{
in this slot call the Class B methods.
}};
Class B
{};
Class C
{signals:
void signalName(); // emit the signal
};