I would like changes to occur in my Qt application whenever a specific QString's value changes. I didn't find any reference to signals in QString
documentation, so do I need to subclass QString
and implement my own signals or are there preferred alternatives?

- 3,402
- 1
- 22
- 60

- 2,745
- 1
- 28
- 39
-
QString does not handle signals since it is a data container, perhaps a possible solution is to add create a class that inherits from QString and implement the signals. – eyllanesc Aug 05 '17 at 12:53
-
2Can't you handle that on whatever class changes the string? – drescherjm Aug 05 '17 at 12:57
2 Answers
You haven't found any reference to signals, because that's not how you get notifications from data classes in Qt. What you need to do is use the property system.
Simply implement the string as a Q_PROPERTY
of some core logic object.
// in some QObject derived class
Q_PROPERTY(QString text MEMBER m_text NOTIFY textChanged)
QString m_text;
signals:
void textChanged();
// that's all you need
It would be a significant overhead to have a lot of strings, each of which inheriting QObject
, as the latter is rather big. However, you can have a lot of strings implemented as a properties of a single object with close to no overhead.
If all you want to do is monitor a string for changes, then a property is all you need. A wrapper around QString
is only justified if you need advanced functionality, notifications not only that the string has changed, but how has it changed, was it cleared, was a particular character replaced, was a bit of it cut or was there another string inserted and where. Kinda what you get for a data model.

- 47,916
- 17
- 112
- 190
A simple solution would be to define your own class with something like this :
class ObservableString : public QObject
{
Q_OBJECT
Q_DISABLE_COPY(ObservableString)
public:
void setValue(const QString &value) {
if (m_string != value) {
m_string = value;
emit valueChanged(value);
}
}
QString value() const {
return m_string;
}
signals:
void valueChanged(QString value);
private:
QString m_string;
};

- 2,119
- 2
- 25
- 45