Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use QObject::setObjectName()?

Tags:

qt

Why should we add an object name to a QObject? I can still load and run any object without setting the name.

like image 489
Dewsworld Avatar asked Apr 04 '12 10:04

Dewsworld


People also ask

What is QObject C++?

QObject is the heart of the Qt Object Model. The central feature in this model is a very powerful mechanism for seamless object communication called signals and slots. You can connect a signal to a slot with connect() and destroy the connection with disconnect().

What is QObject TR?

QObject::tr() translates strings for internationalization. QObject::setProperty() and QObject::property() dynamically set and get properties by name. QMetaObject::newInstance() constructs a new instance of the class.

What is Q_property in QML?

Exposing Properties. A property can be specified for any QObject-derived class using the Q_PROPERTY() macro. A property is a class data member with an associated read function and optional write function. All properties of a QObject-derived or Q_GADGET class are accessible from QML.


2 Answers

Well, it depends on how you plan on getting access to the QObject later. There are several QObject.find() functions that you can use to get access to an QObject. The name adds a "key" to filter your search.

For example, In your own class you probably use instance variables for this instead of doing a search, but you may actually be passed something that you normally don't own, but you know there is a specific button you want to edit (e.g., A QPushButton in one of Qt's built-in QInputDialogs). Giving the button a name makes it easy to find (and is robust if the button disappears, moves in the layout, etc.), whereas checking the button text or counting where it is in the hierarchy would be much more fragile (e.g., button text might change between versions or due to localization, someone adds a new layout, an extra button).

Or you just may want some nice debug text when you are printing pointer values (i.e., you want to know which QObject is causing a problem). It also makes scripting easier, but I won't explain why here.

This is really just the tip of the iceberg. You really only need to set the name if you have a need for it and only you know that answer. :-)

like image 150
Trenton Schulz Avatar answered Oct 14 '22 11:10

Trenton Schulz


You can use the name of the object as an ID Selector in Qt Style Sheets.

Example: if you want a property to apply only to one specific QLineEdit, you can give it a name using QObject::setObjectName() and use an ID Selector to refer to it:

 myDialog->setStyleSheet("QLineEdit#nameEdit { background-color: yellow }");
like image 44
Bill Avatar answered Oct 14 '22 11:10

Bill