QDialog exec() and getting result value - c++

I have subclassed QDialog to implement functionality similar to QMessageBox ( I needed this to allow for customization). It has a text message and OK, Cancel buttons. I am showing the dialog using exec() to make it blocking. Now, how do I return values of true/false when the user clicks on OK/Cancel?
I tried connecting the buttons to setResult() and then, return the result value when clicked, but
Clicking the buttons does not close the dialog box
the return value is incorrect.
Following is the code I have written. I think I am wrong in the exec/result part - but I am not sure how to fix it.
class MyMessageBox : public QDialog {
Q_OBJECT
private slots:
void onOKButtonClicked() { this->setResult(QDialog::Accepted); }
void onCancelButtonClicked() { this->setResult(QDialog::Rejected); }
public:
MyMessageBox(QMessageBox::Icon icon, const QString& title,
const QString& text, bool showCancelButton = true,
QWidget* parent = 0);
virtual void resizeEvent(QResizeEvent* e);
QDialog::DialogCode showYourself()
{
this->setWindowModality(Qt::ApplicationModal);
this->exec();
return static_cast<QDialog::DialogCode>(this->result());
}
};
The user will instantiate the class and call showYourself() which is expected to return the value and also close(and delete) the dialog.
I have posted partial code. Let me know if you need more and I will post the complete version.

Some points :
Rather than using setResult() yourself, use QDialog::accept() and QDialog::reject().
It seems you are not taking full advantage of the signals and slots. You need the object which create the dialog (or another one) to listen to the signals of the dialog.
In your code you are not connecting signals to slots either.
With my fix onOKButtonClicked and onCancelButtonClicked are unnecessary.
With my fix you don't need showYourself(). Just call exec and with the events
information will flow.
You need to add this code before showing the dialog (this assume it is in a dialog method):
QObject::connect(acceptButton, SIGNAL(clicked()), this, SLOT(accept()));
QObject::connect(rejectButton, SIGNAL(clicked()), this, SLOT(reject()));
In the caller object you have
void someInitFunctionOrConstructor(){
QObject::connect(mydialog, SIGNAL(finished (int)), this, SLOT(dialogIsFinished(int)));
}
void dialogIsFinished(int){ //this is a slot
if(result == QDialog::Accepted){
//do something
return
}
//do another thing
}

Another solution:
// set signal and slot for "Buttons"
connect(YesButton, SIGNAL(clicked()), dlg, SLOT(accept()));
connect(NoButton, SIGNAL(clicked()), dlg, SLOT(reject()));
// show modal window event loop and wait for button clicks
int dialogCode = dlg->exec();
// act on dialog return code
if(dialogCode == QDialog::Accepted) { // YesButton clicked }
if(dialogCode == QDialog::Rejected) { // NoButton clicked }

Case 1 Clicking the buttons does not close the dialog box.
For this you have to close the dialog on respective SLOTS, so Use
void onOKButtonClicked(){ this->setResult(QDialog::Accepted); this->close();}
void onCancelButtonClicked(){ this->setResult(QDialog::Rejected);this->close();}
Note: Only after you have clicked the Ok button or Cancel button in a standard QMessageBox, setResult() function is triggered and the status is changed. It's not the same effect when done vice versa.
Case 2 The return value is incorrect.
I think only after your dialog gets closed, you will have the result available in result() function. So I guess it will be solved, after you have made the changes specified in Case 1.
If it still persists, use your own private member function to resolve it.

Related

focusInEvent not called in QLineEdit subclass

I have a Qt/cpp code and display a subclassed QLineEdit. When double-clicking the QLineEdit, the focusInEvent is never called (launched in Maya).
void myQLineEditClass::focusInEvent(QFocusEvent *e)
{
MGlobal::displayInfo(MQtUtil::toMString(QString().sprintf("HERE")));
QLineEdit::focusInEvent(e);
}
HERE is never displayed, event if the focusInEvent is present in the .h protect part. Any idea how to get focusInEvents ?
Try the below. For several occasions that worked for me when focusInEvent did not.
void YourWidget::changeEvent(QEvent* event)
{
if (event->type() == QEvent::ActivationChange)
{
if (isActiveWindow())
{
// gaining the focus
}
else
{
// loosing the focus
}
}
// or whatever *parent* class call is
QWidget::changeEvent(event);
}
The event gets intercepted by the editor widget. See QItemDelegate::createEditor. The widget returned there will get it.
The issue was linked to the fact that the QLineEdit was in a QGraphicsView that was in another QGraphicsView. Bringing the QLineEdit to the higher-level QGraphicsView made it work.

Qt Run Single Application

I have a few dialogs and buttons that call these dialogs. However, every click on the button calls a new dialog window. I want the existing window to close first before the user can click on the button to open another.
Below is an example of a button calling a slot. Whenever I click on the button, it will call a copy of the dialog window. Is there any way to only call one copy of the dialog window only?
Thanks.
Bookmark.cpp:
Bookmark::Bookmark()
{
createButtons();
connect(bookmarkButton, SIGNAL(clicked()), this, SLOT(openBookmarkDlg()));
}
void Bookmark::createButtons()
{
...
bookmarkButton = new QToolButton;
bookmarkButton->setText("Bookmark");
addWidget(bookmarkButton);
...
}
void Bookmark::openBookmarkDlg()
{
BookmarkDlg *bkDlg = new BookmarkDlg;
bkDlg->show();
}
Bookmark.h:
class Bookmark : public QToolBar
{
Q_OBJECT
public:
Bookmark(void);
~Bookmark(void);
public slots:
void openBookmarkDlg();
private:
createButtons();
QToolButton *bookmarkButton;
};
If you want the dialog window to be modal, i.e. the application doesn't accept user input outside the dialog, use the window modality of the dialog.
Beware however that modal windows can be really annoying to users.
If BookmarkDlg inherits QDialog you can do the following:
void Bookmark::openBookmarkDlg()
{
BookmarkDlg *bkDlg = new BookmarkDlg;
prepareYourDialog(bkDlg);
/*If you expect to do something when the dialog is accepted*/
if (bkDlg->exec() == QDialog::Accepted)
{
/*Do something after dialog was accepted, and nothing when canceled*/
}
delete bkDlg;
}
Convert BookmarkDlg *bkDlg into a variable member of the class, instead of a local variable of the method:
private:
createButtons();
QToolButton *bookmarkButton;
BookmarkDlg *bkDlg;
Then on the implementation of the class, you could do:
void Bookmark::openBookmarkDlg()
{
if (!bkDlg)
bkDlg = new BookmarkDlg;
bkDlg->show();
}

Open only one instance of QDialog with show() , and also does the Object is deleted if i close the QDialog

in Qt im opening QDialog windows each time i click some item
im doing it with new , i like to be sure im opening only one instance of QDialog for each item
im clicking :
void foo::treeWidget_itemClicked(QTreeWidgetItem *item,nt column)
.....
QString groupID = item->data(0, Qt::UserRole).toString();
QString groupName = item->text(0);
GroupDialogContainer* pGroupDialogContainer = new GroupDialogContainer(groupID, groupName, this);
pGroupDialogContainer->show();
}
class GroupDialogContainer : public QDialog
{
Q_OBJECT
public:
GroupDialogContainer(QString GroupId,QString GroupName,QWidget *parent=0);
GroupDialogContainer(QWidget *parent=0);
virtual ~GroupDialogContainer();
Ui::GroupDialog ui;
public slots:
void closeEvent(QCloseEvent *event);
};
do i need to keep some kind of hash or vector of GroupDialogContainer ?
also my second question is :
does each time im closing the QDialog window with close () the object pGroupDialogContainer
that was responsible to open it is destroyer ed ? or do i need to delete it when im detecting that the QDIalog has closed?
Yes, you should probably keep some kind of list of your dialogs to keep track of which ones are already open. If your GroupID is your unique ID then you could do something like this:
QMap DialogMap;
void foo::treeWidget_itemClicked(QTreeWidgetItem *item,nt column)
{
.....
QString groupID = item->data(0, Qt::UserRole).toString();
if (! DialogMap.contains(groupID))
{
// Popup the dialog and add it to map
...
DialogMap.insert(groupID, pGroupDialogContainer);
}
}
Now, for the other part. The most important thing is that you need to remove the item from the map when the dialog closes. You could either delete the dialog then, or my suggestion would be to let the dialog delete itself when it closes - as follows:
// set automatic deletion of object on close
setAttribute(Qt::WA_DeleteOnClose);
But as I said, you'll still need to remove the dialog from the Map, or else you'll have a bad pointer in there, and your code will still think the dialog is open.
So you'll need some kind of signal from the dialog to indicate that it is closing. There is the finished(int result) signal, that is called when you trigger a result:
This signal is emitted when the
dialog's result code has been set,
either by the user or by calling
done(), accept(), or reject().
But, you can always create your own signal in your dialog, and emit it when the closeEvent is called in your dialog.
Then in the code that handles the map...
connect( pGroupDialogContainer, SIGNAL(WindowClosed()), this, SLOT(vCleanUpTheMap()));
...
void vCleanUpTheMap()
{
GroupDialogContainer *pDialog = dynamic_cast<GroupDialogContainer *>(sender());
if (pDialog)
{
// Just to keep things clean disconnect from the dialog.
disconnect(pDialog);
// I am assuming that you can get the key groupID from the dialog
// Cause it's a lot easier to remove from a map with the key
DialogMap.remove(pDialog->GetGroupID());
}
}
And that's it.

How to make QDialogButtonBox NOT close its parent QDialog?

I have a QDialog with a QDialogButtonBox widget, and I've connected the button box's accepted signal to a slot in my QDialog subclass, like so:
void MyDialog::on_buttonBox_accepted()
{
QString errorString = this->inputErrorString();
if (errorString.isEmpty())
{
// Do work here
// code code code...
this->accept();
}
else
{
QMessageBox::critical(this, tr("Error"), tr("The following input errors have occurred:") + errorString);
}
}
However, the dialog is closes after the message box is displayed; apparently the button box automatically connects its accepted signal to QDialog's accept slot (I want to call that slot manually). How can I prevent this so I can take the manual approach outlined above?
You can implement MyDialog::accept(). The function is virtual in QDialog.

Prevent a QMenu from closing when one of its QAction is triggered

I'm using a QMenu as context menu. This menu is filled with QActions. One of these QActions is checkable, and I'd like to be able to check/uncheck it without closing the context menu (and having to re-open it again to choose the option that I want).
I've tried disconnecting the signals emitted by the checkable QAction with no luck.
Any ideas? Thanks.
Use a QWidgetAction and QCheckBox for a "checkable action" which doesn't cause the menu to close.
QCheckBox *checkBox = new QCheckBox(menu);
QWidgetAction *checkableAction = new QWidgetAction(menu);
checkableAction->setDefaultWidget(checkBox);
menu->addAction(checkableAction);
In some styles, this won't appear exactly the same as a checkable action. For example, for the Plastique style, the check box needs to be indented a bit.
There doesn't seem to be any elegant way to prevent the menu from closing. However, the menu will only close if the action can actually trigger, i.e. it is enabled. So, the most elegant solution I found is to trick the menu by shortly disabling the action at the moment when it would be triggered.
Subclass QMenu
Reimplement relevant event handlers (like mouseReleaseEvent())
In the event handler, disable the action, then call base class' implementation, then enable the action again, and trigger it manually
This is an example of reimplemented mouseReleaseEvent():
void mouseReleaseEvent(QMouseEvent *e)
{
QAction *action = activeAction();
if (action && action->isEnabled()) {
action->setEnabled(false);
QMenu::mouseReleaseEvent(e);
action->setEnabled(true);
action->trigger();
}
else
QMenu::mouseReleaseEvent(e);
}
To make the solution perfect, similar should be done in all event handlers that may trigger the action, like keyPressEvent(), etc...
The trouble is that it is not always easy to know whether your reimplementation should actually trigger the action, or even which action should be triggered. The most difficult is probably action triggering by mnemonics: you would need to reimplement the complex algorithm in QMenu::keyPressEvent() yourself.
This is my solution:
// this menu don't hide, if action in actions_with_showed_menu is chosen.
class showed_menu : public QMenu
{
Q_OBJECT
public:
showed_menu (QWidget *parent = 0) : QMenu (parent) { is_ignore_hide = false; }
showed_menu (const QString &title, QWidget *parent = 0) : QMenu (title, parent) { is_ignore_hide = false; }
void add_action_with_showed_menu (const QAction *action) { actions_with_showed_menu.insert (action); }
virtual void setVisible (bool visible)
{
if (is_ignore_hide)
{
is_ignore_hide = false;
return;
}
QMenu::setVisible (visible);
}
virtual void mouseReleaseEvent (QMouseEvent *e)
{
const QAction *action = actionAt (e->pos ());
if (action)
if (actions_with_showed_menu.contains (action))
is_ignore_hide = true;
QMenu::mouseReleaseEvent (e);
}
private:
// clicking on this actions don't close menu
QSet <const QAction *> actions_with_showed_menu;
bool is_ignore_hide;
};
showed_menu *menu = new showed_menu ();
QAction *action = menu->addAction (new QAction (menu));
menu->add_action_with_showed_menu (action);
Here are couple ideas I've had... Not sure at all they will work tho ;)
1) Try to catch the Event by using the QMenu's method aboutToHide(); Maybe you can "Cancel" the hide process ?
2) Maybe you could consider using an EventFilter ?
Try to have a look at : http://qt.nokia.com/doc/4.6/qobject.html#installEventFilter
3) Otherwise you could reimplement QMenu to add your own behavior, but it seems a lot of work to me...
Hope this helps a bit !
(I started with Andy's answer, so thank you Andy!)
1) aboutToHide() works, by re-popping the menu at a cached position, BUT it can also enter an infinite loop. Testing if the mouse is clicked outside the menu to ignore re-opening should do the trick.
2) I tried an event filter but it blocks the actual click to the menu item.
3) Use both.
Here is a dirty pattern to prove that it works. This keeps the menu open when the user holds down CTRL when clicking:
# in __init__ ...
self.options_button.installEventFilter(self)
self.options_menu.installEventFilter(self)
self.options_menu.aboutToHide.connect(self.onAboutToHideOptionsMenu)
self.__options_menu_pos_cache = None
self.__options_menu_open = False
def onAboutToHideOptionsMenu(self):
if self.__options_menu_open: # Option + avoid an infinite loop
self.__options_menu_open = False # Turn it off to "reset"
self.options_menu.popup(self.__options_menu_pos_cache)
def eventFilter(self, obj, event):
if event.type() == QtCore.QEvent.MouseButtonRelease:
if obj is self.options_menu:
if event.modifiers() == QtCore.Qt.ControlModifier:
self.__options_menu_open = True
return False
self.__options_menu_pos_cache = event.globalPos()
self.options_menu.popup(event.globalPos())
return True
return False
I say it is dirty because the widget here is acting as an event filter for both the button that opens the menu as well as the menu itself. Using explicit event filter classes would be easy enough to add and it would make things a little easier to follow.
The bools could probably be replaced with a check to see if the mouse is over the menu, and if not, don't pop it open. However, the CTRL key still has to be factored in for my use case, so it probably isn't far off a nice solution as it is.
When the user holds down CTRL and clicks on the menu, it flips a switch so the menu opens itself back up when it tried to close. The position is cached so it opens at the same position. There is a quick flicker, but it feels OK since the user knows they are holding a key down to make this work.
At the end of the day (literally) I already had the whole menu doing the right thing. I just wanted to add this functionality and I definitely didn't want to change to using a widget just for this. For this reason, I am keeping even this dirty patch for now.
Subclass QMenu and override setVisible. You can utilize activeAction() to know if an action was selected and the visible arg to see if the QMenu is trying to close, then you can override and call QMenu::setVisible(...) with the value you want.
class ComponentMenu : public QMenu
{
public:
using QMenu::QMenu;
void setVisible(bool visible) override
{
// Don't hide the menu when holding Shift down
if (!visible && activeAction())
if (QApplication::queryKeyboardModifiers().testFlag(Qt::ShiftModifier))
return;
QMenu::setVisible(visible);
}
};
Connect the QMenu.show to the action trigger. I know this is code for Qt5 (and in Python), but the principle should be back compatible.
from PyQt5 import QtWidgets
class CheckableMenu(QtWidgets.QMenuBar):
def __init__(self,parent=None):
super().__init__(parent)
self.menuObj=QtWidgets.QMenu("View")
self.addMenu(self.menuObj)
for i in ['Both','Even','Odd']: #my checkable items
t=QtWidgets.QAction(i,self.menuObj,checkable=True)
t.triggered.connect(self.menuObj.show)
self.menuObj.addAction(t)
Starting from baysmith solution, the checkbox didn´t work as I was expecting, because I was connecting to the action triggered(), rather than connecting to the checkbox toggled(bool). I´m using the code to open a menu with several checkboxes when I press a button :
QMenu menu;
QCheckBox *checkBox = new QCheckBox("Show Grass", &menu);
checkBox->setChecked(m_showGrass);
QWidgetAction *action = new QWidgetAction(&menu);
action->setDefaultWidget(checkBox);
menu.addAction(action);
//connect(action, SIGNAL(triggered()), this, SLOT(ToggleShowHardscape_Grass()));
connect(checkBox, SIGNAL(toggled(bool)), this, SLOT(ToggleShowHardscape_Grass()));
menu.exec(QCursor::pos() + QPoint(-300, 20));
For my use case, this works like a charm
I have been struggling with this for half a day.
There was many accepted answers on the net suggesting overriding setVisible function of the QMenu which did not work for me at all.
I found a solution based on this post (The last reply by the OP)
my C++ implementation for this matter is as follows:
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
if (event->type() == QEvent::MouseButtonRelease)
{
auto action = static_cast<QMenu*>(watched)->activeAction();
if (action && action->isCheckable())
{
action->trigger();
return true;
}
}
return QObject::eventFilter(watched, event);
}