I have QDialogButtonBox buttons on my dialog which are Ok and Cancel button pair. I have implemented accepted() signal to process when 'Ok' button is pressed but I want to abort quitting dialog if the directory path is invalid.
void SettingsDialog::on_buttonBox_accepted()
{
QDir path( ui->lineEditRootPath->text() );
if ( path.exists( ui->lineEditRootPath->text() ) )
{
QSettings settings; // save settings to registry
settings.setValue(ROOT_PATH, ui->lineEditRootPath->text() );
}
else
{
// abort cancelling the dialog here
}
}
Can the dialog quitting be abort from this handler? Do I have to implement the above code in some other signal? Do I have to use simple button to accomplish this instead of QDialogButtonBox?
This issue comes from the dialog template bundled with Qt Creator. When you create an empty dialog with buttons, the .ui file has connections between the button box and and the underlying dialog. They are created behind your back, so to speak:
So, there really is no problem, since the button box doesn't actually accept the dialog. You must accept the dialog, if you don't then the dialog stays open.
The simple fix is to remove the default connection(s).
Other Nitpicks
You should not use the QDir::exists(const QString &) overload - it won't work. You already provided the path to dir's constructor. Simply use exists().
Thus:
void SettingsDialog::on_buttonBox_accepted()
{
QDir path(ui->lineEditRootPath->text());
if (!path.exists()) return;
QSettings settings; // save settings to registry
settings.setValue(ROOT_PATH, ui->lineEditRootPath->text());
accept(); // accepts the dialog, closing it
}
You could also use the static QFileInfo::exists:
void SettingsDialog::on_buttonBox_accepted()
{
if (! QFileInfo.exists(ui->lineEditRootPath->text()) return;
...
}
Finally, it's probably a nice idea to provide some sort of feedback to the user when an input is invalid. In C++11, that's quite easy to do:
#include <QApplication>
#include <QFileInfo>
#include <QDialog>
#include <QDialogButtonBox>
#include <QLineEdit>
#include <QGridLayout>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QDialog dialog;
QLineEdit edit("/");
QDialogButtonBox buttons(QDialogButtonBox::Ok | QDialogButtonBox::Close);
QGridLayout layout(&dialog);
layout.addWidget(&edit, 0, 0);
layout.addWidget(&buttons, 1, 0);
QObject::connect(&buttons, &QDialogButtonBox::accepted, [&]{
if (!QFileInfo::exists(edit.text())) return;
//...
dialog.accept();
});
QObject::connect(&buttons, &QDialogButtonBox::rejected, [&]{ dialog.reject(); });
QObject::connect(&edit, &QLineEdit::textChanged, [&](const QString&){
if (QFileInfo::exists(edit.text()))
edit.setStyleSheet("");
else
edit.setStyleSheet("* { background: red; }");
});
dialog.show();
return a.exec();
}
After some testing, you've realized that the users have a bad tendency to enter paths that might be on disconnected network volumes. When you attempt to check if they exist, it blocks the GUI just so that the OS can politely tell you "umm, nope".
The solution is to perform the check in a worker thread, so that if it blocks, the UI will not be directly affected. If the worker thread blocks, the path editor background will turn yellow. If the path doesn't exist, the background will turn red and the OK button will be disabled.
One bit of code requires some explanation: QObject::connect(&checker, &Checker::exists, &app, [&](...){...}) connects the checker's signal to a lambda in the thread context of the application object. Since checker's signals are emitted in the checker's thread, without the context (&app), the code would be executed in the checker's thread. We definitely don't want that, the GUI changes must be executed in the main thread. The simplest way to do it is to pass one object we surely know lives in the main thread: the application instance. If you don't pass the proper context, e.g. QObject::connect(&checker, &Checker::exists, [&](...){...})), you'll get undefined behavior and a crash.
#include <QApplication>
#include <QFileInfo>
#include <QDialog>
#include <QDialogButtonBox>
#include <QLineEdit>
#include <QPushButton>
#include <QGridLayout>
#include <QThread>
#include <QTimer>
class Thread : public QThread {
using QThread::run; // final
public:
~Thread() { quit(); wait(); }
};
class Checker : public QObject {
Q_OBJECT
public:
Q_SIGNAL void exists(bool, const QString & path);
Q_SLOT void check(const QString & path) { emit exists(QFileInfo::exists(path), path); }
};
int main(int argc, char *argv[])
{
bool pathExists = true;
QApplication app(argc, argv);
QDialog dialog;
QLineEdit edit("/");
QDialogButtonBox buttons(QDialogButtonBox::Ok | QDialogButtonBox::Close);
QGridLayout layout(&dialog);
layout.addWidget(&edit, 0, 0);
layout.addWidget(&buttons, 1, 0);
QTimer checkTimer;
Checker checker;
Thread checkerThread;
checker.moveToThread(&checkerThread);
checkerThread.start();
checkTimer.setInterval(500);
checkTimer.setSingleShot(true);
QObject::connect(&buttons, &QDialogButtonBox::accepted, [&]{
if (!pathExists) return;
//...
dialog.accept();
});
QObject::connect(&buttons, &QDialogButtonBox::rejected, [&]{ dialog.reject(); });
QObject::connect(&edit, &QLineEdit::textChanged, &checker, &Checker::check);
QObject::connect(&edit, &QLineEdit::textChanged, &checkTimer, static_cast<void (QTimer::*)()>(&QTimer::start));
QObject::connect(&checkTimer, &QTimer::timeout, [&]{ edit.setStyleSheet("background: yellow"); });
QObject::connect(&checker, &Checker::exists, &app, [&](bool ok, const QString & path){
if (path != edit.text()) return; // stale result
checkTimer.stop();
edit.setStyleSheet(ok ? "" : "background: red");
buttons.button(QDialogButtonBox::Ok)->setEnabled(ok);
pathExists = ok;
});
dialog.show();
return app.exec();
}
#include "main.moc"
Related
I would like to find an easy way to start a lengthy operation from my application's main gui thread. I have his exporter object that is not affiliated to any thread.
void closeExporter()
{
// Run closing of object in a different thread:
QFuture<void> future = QtConcurrent::run([=]()
{
m_pExporter->close();
});
while (!future.isFinished())
{
QApplication::processEvents();
// QThread::msleep(0);
qDebug() << "waiting!";
}
}
I am not using waitForFinished() function then it blocks any my gui thread becomes unresponsive. It works fine for a while put the debug printing stop and my application will still become unresponsive. Dies somebody have an idea why this is happening?
I think, that you should use QFutureWatcher as a possible implementation. The following small example illustrates the usage.
#include <QApplication>
#include <QFrame>
#include <QDebug>
#include <QHBoxLayout>
#include <QPushButton>
#include <QThread>
#include <QObject>
#include <QFutureWatcher>
#include <QMessageBox>
#include <QtConcurrent>
int main(int argc, char* argv[])
{
QApplication a(argc, argv);
auto frame = new QFrame;
frame->setLayout(new QHBoxLayout);
auto btn = new QPushButton("Start Thread");
frame->layout()->addWidget(btn);
QThread::currentThread()->setObjectName("Main Thread");
QFutureWatcher<void> watcher;
QObject::connect(&watcher, &QFutureWatcher<void>::finished, [frame,btn]() {
QMessageBox::information(frame, "Done", QThread::currentThread()->objectName(), QMessageBox::StandardButton::Ok);
btn->setEnabled(true);
});
QObject::connect(btn, &QPushButton::clicked, [btn,&watcher](){
QFuture<void> future = QtConcurrent::run([]() {
QThread::msleep(6000);
qDebug() << QThread::currentThread()->objectName();
});
watcher.setFuture(future);
btn->setDisabled(true);
});
frame->show();
return a.exec();
}
The original code was working fine after all. Sorry to burn your time.
I migrated some code from Qt 5.6.0 to 5.12.0. Suprisingly, I'm getting lots of warnings related to QWindowsWindow::setGeometry. Whenever a dialog is shown on top of another, I get this warning.
I could isolate the problem in a MCVE, it's very simple and minimal, all parenting look good, however, we get the warning when button is pressed:
QWindowsWindow::setGeometry: Unable to set geometry 132x30+682+303 on QWidgetWindow/'QDialogClassWindow'. Resulting geometry: 132x42+682+303 (frame: 4, 28, 4, 4, custom margin: 0, 0, 0, 0, minimum size: 116x42, maximum size: 16777215x16777215).
main.cpp:
#include <QApplication>
#include "mainframe.h"
#include <qDebug>
void MessageOutput( QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
qDebug() << msg;
}
int main( int argc, char* argv[] )
{
QApplication app(argc, argv);
qInstallMessageHandler(MessageOutput);
MainFrame wnd;
wnd.show();
return app.exec();
}
mainframe.h:
#include <QMainWindow>
class QPushButton;
class MainFrame : public QMainWindow
{
Q_OBJECT
public:
MainFrame();
public slots:
void showPopup();
private:
QPushButton* button;
};
mainframe.cpp:
#include "mainframe.h"
#include <QDialog>
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
MainFrame::MainFrame()
{
QWidget* widget = new QWidget( this );
widget->setLayout( new QVBoxLayout( widget ) );
QPushButton* pTextButton = new QPushButton( "Show popup", widget );
widget->layout()->addWidget( pTextButton );
connect( pTextButton, SIGNAL(clicked()), this, SLOT(showPopup()) );
setCentralWidget( widget );
}
void MainFrame::showPopup()
{
QDialog dlg( this );
dlg.setLayout( new QVBoxLayout() );
dlg.layout()->addWidget( new QLabel("popup message",&dlg) );
dlg.exec();
}
I see the issue under Windows 7 and 10. Am I doing anything wrong?
I know the warning can be removed by setting setMinimumSize (see https://stackoverflow.com/a/31231069/3336423), but why should we do this for every widget we create? Is there a way to fix that for good?
As you mentioned, this problem occurs only in Windows: the QWindowsWindow class is part of the windows platform plugin. Looking at Qt's source code (qwindowswindow.cpp#QWindowsWindow::setGeometry) there is no direct way to pause that specific message.
The only global solution I can think of right now is to filter the warning messages using a message handler:
void myMessageOutput(QtMsgType type, const QMessageLogContext& context, const QString& msg)
{
if (type != QtWarningMsg || !msg.startsWith("QWindowsWindow::setGeometry")) {
QByteArray localMsg = msg.toLocal8Bit();
fprintf(stdout, localMsg.constData());
}
}
int main(int argc, char* argv[])
{
qInstallMessageHandler(myMessageOutput);
QApplication a(argc, argv);
// ...
}
UPDATE
One of the problems is that Windows adds its own buttons to the frame. In your example the dialog adds three buttons: the system button (the icon, top-left corner), the help button and the close button. The help and close buttons have a fixed size, which happens to be larger than the QDialog's frame (which is computed as the maximum between the requested size and minimumSize). This then generates the warning: your requested size doesn't match the one created by Windows:
If you remove the help button, for example (dlg.setWindowFlags(dlg.windowFlags() & ~Qt::WindowContextHelpButtonHint);), the warning disappears without setting a minimum size for the window. A manual action must be taken for each dialog displayed, but I think it is easier to automatize than the minimum size (through a factory maybe?):
The issue was reported to Qt:
https://bugreports.qt.io/browse/QTBUG-73258
To the code in OP is OK, it's just a Qt bug.
It's marked as "P2 Important", so hopefully it should be fixed in a next release.
Update: It's still not fixed in Qt 6.2.2...
My task is to write an automated UI test for a software being developed. It happens so, that there are radiobuttons triggering a messagebox, which stops my automated test until I manually confirm it (pressing ENTER). The issue is that I do not know how I can call that newly summoned messagebox and then have it confirmed by QTest::keyClick(<object>, QtKey::Key_Enter); and have my automated test continue the run.
I am using QWidgets, QApplication, Q_OBJECT and QtTest.
I will provide a code similar to what I am working with:
void testui1(){
Form1* myform = new Form1();
myform->show();
QTest::mouseClick(myform->radioButton01, Qt::LeftButton, Qt::NoModifier, QPoint(), 100);
// Message box pops up and stops the operation until confirmed
QTest::mouseClick(myform->radioButton02, Qt::LeftButton, Qt::NoModifier, QPoint(), 100);
// again
...
}
How exactly can I script to confirm the message box automatically? The message box is only an [OK] type, so I don't need it to return whether I have pressed Yes or No. A QTest::keyClick(<target object>, Qt::Key_Enter) method needs to know to which object it should press enter to. I tried including myform into the object and it did not work. Googling I did not find the answer. I found the following result as not functioning for what I am looking for
QWidgetList allToplevelWidgets = QApplication::topLevelWidgets();
foreach (QWidget *w, allToplevelWidgets) {
if (w->inherits("QMessageBox")) {
QMessageBox *mb = qobject_cast<QMessageBox *>(w);
QTest::keyClick(mb, Qt::Key_Enter);
}
}
The problem is that once you've "clicked" on your radio button, which results in QMessageBox::exec being called, your code stops running until the user clicks on of the buttons.
You can simulate the user clicking a button by starting a timer before you click on the radio button.
In the callback function for the timer you can use QApplication::activeModalWidget() to obtain a pointer to the message box, and then just call close on it.
QTimer::singleShot(0, [=]()
{
QWidget* widget = QApplication::activeModalWidget();
if (widget)
widget->close();
});
If you want to press a specific key on the message box, you can use QCoreApplication::postEvent to post a key event to the message box
QTimer::singleShot(0, [=]()
{
int key = Qt::Key_Enter; // or whatever key you want
QWidget* widget = QApplication::activeModalWidget();
if (widget)
{
QKeyEvent* event = new QKeyEvent(QEvent::KeyPress, key, Qt::NoModifier);
QCoreApplication::postEvent(widget, event);
}
});
So in terms of how this ties into the sample code you gave:
void testui1()
{
Form1* myform = new Form1();
myform->show();
QTimer::singleShot(0, [=]()
{
QWidget* widget = QApplication::activeModalWidget();
if (widget)
widget->close();
else
QFAIL("no modal widget");
});
QTest::mouseClick(myform->radioButton01, Qt::LeftButton, Qt::NoModifier, QPoint(), 100);
}
A sample app putting all the above together:
#include <QApplication>
#include <QMainWindow>
#include <QHBoxLayout>
#include <QPushButton>
#include <QTimer>
#include <QMessageBox>
#include <iostream>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QMainWindow window;
QWidget widget;
window.setCentralWidget(&widget);
QHBoxLayout layout(&widget);
QPushButton btn("go");
layout.addWidget(&btn);
QObject::connect(&btn, &QPushButton::clicked, [&]()
{
QTimer::singleShot(0, [=]()
{
QWidget* widget = QApplication::activeModalWidget();
if (widget)
{
widget->close();
}
else
{
std::cout << "no active modal\n";
}
});
QMessageBox(
QMessageBox::Icon::Warning,
"Are you sure?",
"Are you sure?",
QMessageBox::Yes | QMessageBox::No,
&window).exec();
});
window.show();
return app.exec();
}
Clicking on Go will look like nothing is happening, as the QMessageBox is closed immediately.
To prove that the message box is shown and then closed you can increase the time in the call to QTimer::singleShot to a value such as 1000. Now it will show the message box for 1 second, and then it will be closed by the timer.
I'm using QFileDialog::getOpenFileName right now. However, as suggested in this article, this crashes when the main application closes while the dialog is open. You can see an example of how to reproduce the crash here:
int main(int argc, char **argv) {
QApplication application{argc, argv};
QMainWindow *main_window = new QMainWindow();
main_window->show();
QPushButton *button = new QPushButton("Press me");
main_window->setCentralWidget(button);
QObject::connect(button, &QPushButton::clicked, [main_window]() {
QTimer::singleShot(2000, [main_window]() { delete main_window; });
QFileDialog::getOpenFileName(main_window, "Close me fast or I will crash!");
});
application.exec();
return 0;
}
I can use QFileDialog with the normal constructor instead, as described here. However, then I don't seem to get the native windows file open dialog.
Is there a way to get a non crashing program and use the native Windows file open dialog through Qt?
If you close your main_window instead of deleting it, you won't get any crash.
By the way, you could check if there is any QFileDialog opened to avoid a wrong app exit.
In the next example, I'm closing the dialog, but you could implement another solution:
#include <QTimer>
#include <QApplication>
#include <QMainWindow>
#include <QPushButton>
#include <QFileDialog>
#include <QDebug>
int main(int argc, char **argv) {
QApplication application{argc, argv};
QMainWindow *main_window = new QMainWindow();
main_window->show();
QPushButton *button = new QPushButton("Press me");
main_window->setCentralWidget(button);
QObject::connect(button, &QPushButton::clicked, [main_window]() {
QTimer::singleShot(2000, [main_window]() {
QObjectList list = main_window->children();
while (!list.isEmpty())
{
QObject *object= list.takeFirst();
if (qobject_cast<QFileDialog*>(object))
{
qDebug() << object->objectName();
QFileDialog* fileDialog = qobject_cast<QFileDialog*>(object);
fileDialog->close();
}
}
main_window->close();
});
QFileDialog::getOpenFileName(main_window, "Close me fast or I will crash!");
});
application.exec();
return 0;
}
The design of your application is broken. The shut down of the application normally happens when the outernmost event loop in the main thread exists. This won't happen while a file dialog is active - by definition, its event loop is running then. Thus you're doing something you shouldn't be doing, and the file dialog is merely a scapegoat, or a canary in the coalmine indicating brokenness elsewhere.
There is a QApplication::lastWindowClosed() signal. The Qt docs say:
This signal is emitted from QApplication::exec()
when the last visible primary window [...] is closed.
However, I used QApplication::processEvents() instead of QApplication::exec() in a loop. See this minimal example. (save as qapp.h, it must end on .h, and run qmake -project && qmake && make)
#include <QApplication>
#include <QDebug>
#include <QObject>
#include <QMainWindow>
int exitprogram = 0;
class MyMainWindow : public QMainWindow
{
Q_OBJECT
public slots:
void request_exit() {
qDebug() << "exit requested";
exitprogram = 1;
}
};
int main(int argc, char** argv)
{
QApplication app(argc, argv);
MyMainWindow w;
QObject::connect(&app, SIGNAL(lastWindowClosed()),
&w, SLOT(request_exit()));
w.show();
while(!exitprogram)
{
app.processEvents(QEventLoop::AllEvents, 20);
}
}
Is there still a good way to find out, or to even get a signal, if the last such window is being closed?
Whatever reason you have for using processEvents in place of exec is wrong. The two are not equivalent. exec() will, for example, process the deferred deletion events, while processEvents will not. As you've just found out, the lastWindowClosed signal is not emitted either. This should be telling you right there that you're doing it wrong.
The idiomatic Qt way of doing something each time the event loop goes for another iteration, is to use a zero-timeout timer. Those are virtual timers that do not use operating system resources, they are an internal Qt construct.
The example below illustrates the following:
Use of a zero-timeout timer within a QObject.
Use of the State Machine Framework to manage the state of the application. We have three states:
sWindows is the state when the application windows are still shown. The application is set not to quit on the last window being closed.
sSetup is the state reached when the last of the windows was closed. In this state we ask our Object to send its notification signal with the number of times it executed the zero-timeout timer. This will set the proper count in the message label (C++11 code) or in the count label (legacy code). The state machine automatically transitions to the following state.
sMessage is the state when the message labels are shown, and the application is set to quit upon the last window being closed.
The use of a state machine leads to declarative code: you tell the state machine how to behave, without implementing all of the behavior. You only have to implement the behaviors that are specific to your application and not already provided by Qt. The objects that the state machine manages can be very much decoupled, and the code that declares the behavior of the machine is cohesive - it can be all in one function, instead of being spread around. This is considered to be good software design.
Do note that the zero-timeout timer is very diligent: it will force your handler code to execute constantly whenever the event loop is empty. This will force 100% CPU consumption on the core where the GUI thread happens to be executing. If you have nothing to do, you should stop() the timer.
Qt 5 C++11 Code
// https://github.com/KubaO/stackoverflown/tree/master/questions/close-process-19343325
#include <QtWidgets>
int main(int argc, char** argv)
{
QApplication app{argc, argv};
QLabel widget{"Close me :)"};
QLabel message{"Last window was closed"};
int counter = 0;
auto worker = [&]{
counter++;
};
QTimer workerTimer;
QObject::connect(&workerTimer, &QTimer::timeout, worker);
workerTimer.start(0);
QStateMachine machine;
QState sWindows{&machine};
QState sSetup {&machine};
QState sMessage{&machine};
sWindows.assignProperty(qApp, "quitOnLastWindowClosed", false);
sWindows.addTransition(qApp, &QGuiApplication::lastWindowClosed, &sSetup);
QObject::connect(&sSetup, &QState::entered, [&]{
workerTimer.stop();
message.setText(QString("Last window was closed. Count was %1.").arg(counter));
});
sSetup.addTransition(&sMessage);
sMessage.assignProperty(&message, "visible", true);
sMessage.assignProperty(qApp, "quitOnLastWindowClosed", true);
machine.setInitialState(&sWindows);
machine.start();
widget.show();
return app.exec();
}
Qt 4/5 C++11 Code
#include <QApplication>
#include <QLabel>
#include <QStateMachine>
#include <QBasicTimer>
class Object : public QObject {
Q_OBJECT
QBasicTimer m_timer;
int m_counter = 0;
protected:
void timerEvent(QTimerEvent * ev) {
if (ev->timerId() == m_timer.timerId())
m_counter ++;
}
public:
Object(QObject * parent = 0) : QObject{parent} {
m_timer.start(0, this);
}
Q_SLOT void stop() const {
m_timer.stop();
emit countedTo(m_counter);
}
Q_SIGNAL void countedTo(int) const;
};
int main(int argc, char** argv)
{
QApplication app{argc, argv};
Object object;
QLabel widget{"Close me :)"};
QLabel message{"Last window was closed"};
QLabel count;
QStateMachine machine;
QState sWindows{&machine};
QState sSetup{&machine};
QState sMessage{&machine};
sWindows.assignProperty(qApp, "quitOnLastWindowClosed", false);
sWindows.addTransition(qApp, "lastWindowClosed()", &sSetup);
object.connect(&sSetup, SIGNAL(entered()), SLOT(stop()));
count.connect(&object, SIGNAL(countedTo(int)), SLOT(setNum(int)));
sSetup.addTransition(&sMessage);
sMessage.assignProperty(&message, "visible", true);
sMessage.assignProperty(&count, "visible", true);
sMessage.assignProperty(qApp, "quitOnLastWindowClosed", true);
machine.setInitialState(&sWindows);
machine.start();
widget.show();
return app.exec();
}
#include "main.moc"
I modified your code and now it works. I override closeEvent
==> test.cpp <==
#include "windows.hpp"
int exitprogram = 0;
int main(int argc, char** argv)
{
QApplication app(argc, argv);
MyMainWindow w;
w.show();
while(!exitprogram)
{
app.processEvents(QEventLoop::AllEvents, 20);
}
}
==> test.pro <==
TEMPLATE = app
TARGET = test
QT += widgets
INCLUDEPATH += .
HEADERS += windows.hpp
# Input
SOURCES += test.cpp
==> windows.hpp <==
#include <QApplication>
#include <QDebug>
#include <QObject>
#include <QMainWindow>
#include <QCloseEvent>
extern int exitprogram;
class MyMainWindow : public QMainWindow
{
Q_OBJECT
public slots:
void closeEvent(QCloseEvent *event) override {
exitprogram = 1;
event->accept();
}
};