Reputation: 2009
I have subclassed QDialog
and I have created a const
method, because I want to definitely prevent modifications of my instance. Now if a certain error occurs, I would like to use a QMessageBox
to display it. But I can't use this
as the parent of the message box, because this
is const
.
This is a pity. According to the documentation (https://doc.qt.io/qt-5/qdialog.html#QDialog) the parent influences the default location of the new dialog and whether it shares the parent's taskbar entry. Does the parent necessarily have to be non-const
for that...?
I see three options, none of them being obviously excellent:
const_cast
(seems strange to me to use const_cast
in such a common situation)nullptr
as parent (ugly, because the message box position is worse)Is Qt not const-correct when it demands the parent widget to be modifiable? And is there a better solution than the const_cast
?
Upvotes: 4
Views: 400
Reputation: 8220
One of the reason to introduce ..._cast
methods is to differntiate data castind and same time to protect from unwanted casting and make code more readable and easy search in code.
Operator const_cast
is exactly that thing for your taks. The mark const
in method mean that your operations will not modify any object state data. However make alert dialog or any window require modify much states in operation system and application internal data. That is the reason why it is not const opearations.
However apper and close alert dialog is not change any state in data of your object and not concern your task. So in point o view os and application state management create dialog is not const. But in ponit of view of task which you solve in your application the apearance of alert dialog is a const operation.
Therefore const_cast
is exactly that what you need to make join of different tasks where them is intersected.
Upvotes: 1