Qt Dialog X Button Override Reject Not Working As Expected - c++

I have been trying to hide a stand alone dialog application when the user hits the typical close button (The one with the X in the corner usually next to the minimize button) I cam across this post:
Qt: How do I handle the event of the user pressing the 'X' (close) button?
which I thought would have my solution, but I get strange behavior when I implement it.
void MyDialog::reject()
{
this->hide()
}
When I hit the X Button the whole application closes (the process disappears) which is not what I want. Since my gui spawns with a command line, I setup a test system where I can tell my dialog to hide via a text command where I call the same 'this->hide()' instruction, and everything works fine. The dialog hides and then shows back up when I tell it to show.
Any ideas why the reject method is closing my app completely even when I don't explicitly tell it to?

Override the virtual function "virtual void closeEvent(QCloseEvent * e)" in your dialog class. The code comment will explain in detail.
Dialog::Dialog(QWidget *parent) :QDialog(parent), ui(new Ui::Dialog){
ui->setupUi(this);
}
Dialog::~Dialog(){
delete ui;
}
//SLOT
void Dialog::fnShow(){
//Show the dialog
this->show();
}
void Dialog::closeEvent(QCloseEvent *e){
QMessageBox::StandardButton resBtn = QMessageBox::question( this, "APP_NAME",
tr("Are you sure?\n"),
QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
QMessageBox::Yes);
if (resBtn != QMessageBox::Yes){
//Hiding the dialog when the close button clicked
this->hide();
//event ignored
e->ignore();
//Testing. To show the dialog again after 2 seconds
QTimer *qtimer = new QTimer(this);
qtimer->singleShot(2000,this,SLOT(fnShow()));
qtimer->deleteLater();
}
//below code is for understanding
//as by default it is e->accept();
else{
//close forever
e->accept();
}
}

Related

Qt, QDialog buttons not Respondig

The dialog opens with two buttons, OK and Cancel. None of the buttons responds to user click. I have to press the X on the top right to cancel the dialog.
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
if (obj == mTabWidget && event->type() == QEvent::MouseButtonDblClick)
{
// query and set tab(s) names
QTabWidget *tab = qobject_cast<QTabWidget *>(obj);
if(tab)
{
QDialog dlg;
QVBoxLayout la(&dlg);
QLineEdit ed;
la.addWidget(&ed);
QDialogButtonBox bb(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
la.addWidget(&bb);
dlg.setLayout(&la);
if(dlg.exec() == QDialog::Accepted)
{
tab->setTabText(0, ed.text());
return true;
}
}
}
// Standard event processing
return QObject::eventFilter(obj, event);
}
Am I missing any connect() line or signals? I tried to read the Qt documentation, but from what I understood, calling QDialogButtonBox::OK gets processed as Accepted.
UPDATE :
New Dialog Function
OK, i have created a new function that takes care of the Dialog box, i am calling it from the event function. it is still not responding, now on the terminal, i see an error that says, : no such slot MainWindow::accept() and another for reject. I know that i have no slots for these two in the .h file. i tried to find how to build the slots but i couldnt, any help would be great. thank you
void MainWindow::initializeBOX()
{
QDialog dlg;
QVBoxLayout la(&dlg);
QLineEdit ed;
la.addWidget(&ed);
//QDialogButtonBox bb(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
//btnbox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
la.addWidget(buttonBox);
dlg.setLayout(&la);
if(dlg.exec() == QDialog::Accepted)
{
mTabWidget->setTabText(0, ed.text());
}
}
Rather than launching the dialog from event filer you should trap QWidget::mouseDoubleClickEvent by overloading that virtual function in your code. And as long as it is a callback already you can do more stuff immediately from there including the dialog. Or maybe send the signal to slot that does the dialog (a bit cleaner). I would do the signal from mouseDoubleClickEvent event handler and make the parent QWidget::mouseDoubleClickEvent to consume the event to avoid possible complications especially when porting the code to other platform.
Event filters are for non-standard event processing. There is nothing non-standard in your case.

Qt: "No such signal" error

I have a simple code; here I've two buttons, I press the first one and it shows a MsgBox. Then I press the "Okay", and it should call a connected action written in a second button, but it doesn't. Instead I get an error:
Object::connect: No such signal QMessageBox::buttonClicked(QMessageBox::Ok)
Object::connect: (receiver name: 'OpenFile_Bttn')
The code:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_OpenFile_Bttn_clicked(){
QFileDialog::getOpenFileName(this,tr("Open file"), "", tr(""));//Open a dialog "OpenFile"
}
void MainWindow::on_pushButton_clicked(){
QMessageBox msgBox;
msgBox.setText("Push button to choose a file");
//Connect clicking button in MsgBox to an action in OpenFile_Bttn button
QWidget::connect(&msgBox,SIGNAL(buttonClicked(QMessageBox::Ok)),
ui->OpenFile_Bttn, SLOT(on_OpenFile_Bttn_clicked()));
msgBox.exec();//Show MsgBox
}
Also I found an interesting thing, that the error message appears when a MsgBox popup, but not when I click the button "Ok" inside the MsgBox.
No need for signals here, exec returns the button clicked.
void MainWindow::on_OpenFile_Bttn_clicked(){
QFileDialog::getOpenFileName(this,tr("Open file"), "", tr(""));//Open a dialog "OpenFile"
}
void MainWindow::on_pushButton_clicked(){
QMessageBox msgBox;
msgBox.setText("Push button to choose a file");
//Connect clicking button in MsgBox to an action in OpenFile_Bttn button
if(msgBox.exec() == QMessageBox::Ok)
{
on_OpenFile_Bttn_clicked();
}
}
If you want to use custom buttons you can still call msgBox.buttonClicked() after exec to find out which button was clicked.
If you do this instead you get a compiler error, that way you can see something is wrong at compile instead of runtime error
QObject::connect(msgBox, &QMessageBox::buttonClicked, ui->OpenFile_Bttn, &QPushButton::clicked);
out of interest the above code is untested and probably wont compile but basicallt just do sender, signal, reciever, slot but use their class object to select signal and slots like shown above and then you will get an easier to spot compile error that tells you what could be wrong

Restore maximized/normal window after launching minimized app in QT

I have a problem with my Qt app. I can save and restore qeometry of my app without any problem. The problem is when I try to saveGeometry of maximized app in close event and after that I try to start the some app minimized (something like "Run mimimized on startup"). When I do that and I clicked icon on a taskbar the window is open as normal window (not maximized).
I can image (and write) some workaround but with all Gui logic it's easy to do some mistake that I prefere some native way. I'm looking for something like parametr when I could set that window after minimalization should be maximized or normal.
I don't have this problem when I start app maximized, next I minimize window and again maximize. In this case everything is ok. Problem is only on startup.
It look like small detail but it is big think if we think on app which people use everyday and they can't have everyday the some window.
EDIT:
After few hours I give up.
Here is my workaround. Not deeply tested yet, but mayby somebody needs it in the future.
I'll edit it if I find some error or better solution.
#include "mainwindow.h"
#include <QSettings>
#include <QCloseEvent>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), settings("MyCompany", "MyApp") {
settingsReaded = false;
startMinimized = true;
if(startMinimized) showMinimized();
else show();
}
void MainWindow::closeEvent(QCloseEvent *event) {
settings.setValue("geometry", saveGeometry());
showMinimized();
event->ignore();
}
void MainWindow::readSettings() {
restoreGeometry(settings.value("geometry").toByteArray());
settingsReaded = true;
}
void MainWindow::changeEvent(QEvent * event) {
bool isActive = (event->type() == QEvent::ActivationChange && isActiveWindow());
//load settings on first window activation (click on icon of minimized window or
//open window if we have startMinimized = false
//settingsReaded - determine that the settings was loaded only once.
if(isActive && !settingsReaded) {
readSettings();
}
}

Qt Browser stack when dropping link to QMainWindow

I have simple drag and drop functions implemented in QmainWindow the reference taken from here and here
all i want to do is to accept valid url and open QDialog when the url dropped .
but when the url drooped and the QDialog poped up the browser is stocked in the background until i close the QDialog . this is wrong the browser should be free all the time.
here is my code :
void MainWindow::dragMoveEvent(QDragMoveEvent *event)
{
if (event->mimeData()->hasFormat("text/html"))
{
event->acceptProposedAction();
}
else
{
event->ignore();
}
}
void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
// accept just text/uri-list mime format
if (event->mimeData()->hasFormat("text/html"))
{
event->acceptProposedAction();
}
else
{
event->ignore();
}
}
void MainWindow::dragLeaveEvent(QDragLeaveEvent *event)
{
event->accept();
}
void MainWindow::dropEvent(QDropEvent *event)
{
QList<QUrl> urlList;
QString fName;
QStringList pathList;
QFileInfo info;
QString suffix;
if (event->mimeData()->hasFormat("text/html"))
{
urlList = event->mimeData()->urls(); // returns list of QUrls
// if just text was dropped, urlList is empty (size == 0)
if ( urlList.size() > 0) // if at least one QUrl is present in list
{
QString url = urlList.at(0).toString();
event->acceptProposedAction();
openDialog(url); // THIS IS THE FUNCTION THAT I OPEN THE QDIALOG window
}
}
//event->acceptProposedAction();
}
void MainWindow::openDialog(QString& slink)
{
QHash<QString,QVariant> DataMap;
QString link = slink;
DataMap.insert("m_webpage",link);
PublishToDialog* pPublishToDialog = new PublishToDialog(this);
pPublishToDialog->Init(DataMap);
if(pPublishToDialog->exec() != QDialog::Accepted)
{
}
}
when i remove the call to the QDialog , so every thing is working fine .
and the browser doesn't stuck. i even tryed as suggested using signal/slot put again
when i start the QDialog when drop invoked the browser stucked!
What exactly is PublishToDialog? I would assume that it is a custom dialog implementation of yours that inherits QDialog. And given this line:
pPublishToDialog->exec() != QDialog::Accepted
This opens the dialog as a modal dialog. A modal dialog is blocking and will block the execution of the current thread until some action is performed on the dialog. Instead of using a modal dialog, you should use a non-modal dialog. Since I am still not sure if PublishToDialog inherits QDialog or what else, I am just going to assume it is. Here is what you could do:
PublishToDialog* pPublishToDialog = new PublishToDialog(this);
// Make it a non-modal dialog
pPublishDialog->setModal(false);
// Connect it to a slot to handle whenever the user performs some action on it
QObject::connect(pPublishDialog, SIGNAL(finished()), this, SLOT(handleDialogAction());
pPublishDialog.show();
You will have to implement handleDialogAction in your code. At the same time, you may want to make pPublishDialog a class-member as you will need it to access QDialog::reuslt in handleDialogAction.

QDialog not closing right away when pressing the X, how to make it NOT on top?

I open QDialog window from QMainWindow. Now when I press the QDialog window
its not always closing in the first press - I need to press few times (3-4) to close it .
I have closeEvent slot that has simple event->accept(); inside it.
This is how I call the QDialog from the main window:
void MyManager::DialogContainerOpen(type t)
{
if(pMyDialogContainer == NULL)
{
pMyDialogContainer = new MyDialogContainer();
}
int returnVal = QDialog::Rejected;
if(!m_bContainer)
{
m_bContainer = true;
int returnVal = pMyDialogContainer->exec();
if(returnVal != QDialog::Accepted ) {
m_bContainer = false;
}
}
}
This is the first problem.
The second problem is how do i set the QDialog windows NOT to be allays on top? (I don’t want it to block the parent window.
UPDATE
well i found out that the function from the MainWindow that showing the contexMenu
and inside it has the connect single/slot is keeps to invoke so i just used the disconnect
i dont know if its the best sulotion but its working.
now i juat have the final problem .
here is the code i hope its ok
void MainWindowContainer::ShowContextMenu(const QPoint& pos) // this is a slot
{
QModelIndex modelIndx;
QPoint globalPos = ui.treeView_mainwindow->mapToGlobal(pos);
bool b1 = connect(OpenAction, SIGNAL(triggered()),m_SignalMapper, SLOT(map()) );
m_SignalMapper->setMapping(OpenAction,voidID);
bool b2 = connect(m_SignalMapper, SIGNAL(mapped(QString)), this, SLOT(OpenWin(QString)));
QAction* selectedItem = ContextMenu.exec(globalPos);
}
void MainWindowContainer::OpenWin(QString gid)
{
//disconnect(sender0, SIGNAL(overflow()),receiver1, SLOT(handleMathError()));
disconnect(m_SignalMapper, SIGNAL(mapped(QString)),this, SLOT(OpenWin(QString)));
disconnect(OpenAction,SIGNAL(triggered()),m_SignalMapper, SLOT(map()));
....
....
}
For your second question, the term you are looking for is modal vs modeless dialogs. The QDialog documentation tells exactly how you create non-modal dialogs:
Modeless dialogs are displayed using show(), which returns control to the caller immediately.
i.e. don't use exec() as that will make a modal dialog (which blocks the parent).
You should not connect the same signal/slot more than once unless you want the action run multiple times. All you need to do is to connect the QAction's signal to the slot once. This is usually done in the constructor (or a dedicated function called from the constructor) where you create the action.