Unsolved Defining QString to be used in several classes
-
Hi,
How can I define a QString variable to be able to use it in several classes?
Thank you. -
Hi
Best design is with signals and slots.The QString class lives in one class and when changed, the owner class emits the string to the other classes.
They can then keep a copy.Globals variables are not a good idea.
-
@mrjj
If I assign a value to a variable in the program, is there a signal I can use to send the value to the other class? -
@gabor53 you need to define one
-
@gabor53
No really, you should just define a new signal.
If you use a setter function , you can emit there.
pseudo code:class MyStrOwner : QObject { Q_OBJECT private: QString Name; // let just say its name signals; void NameChanged( QString ); public; void setName( QString NewName) { Name=NewName; emit NameChanged(Name); } }
Then if u say anywhere
MyStrOwner oneclass;
oneclass.setName("hello");it will auto emit
-
@mrjj
Thank you! -
Hi,
Just a fix to @mrjj code. In the
setName
slot:void setName( QString newName) { if (newName == name) { return; } name = newName; emit nameChanged(name); }
Otherwise you can trigger a signal storm if you connect the
nameChanged
signal to an object that has a connection to thesetName
slot following the same approach. -
@mrjj what about QSharedData or similar from that QShared* classes. Well, the signal might still be needed for detecting a change, but you do not need to copy the data …
-
@Wurgl said in Defining QString to be used in several classes:
QSharedData
You are right. That would be the right way if programmer
want to share and update same data.I just saw "be able to use it in several classes?" and though
about global variables and how not to do it :)@SGaist
Thank you. :)