"please wait" during long operation in Qt? - qt

I need to do an operation after a user clicking a button, and that may take some time. How can I display a "busy" or "please wait" icon/message (like a spinning circle etc) and prevent a user from clicking the button again (or some other buttons) during the time? Thanks.

Use your QApplication object's static function setOverrideCursor(const QCursor &cursor)
Set the wait cursor, to make the application "busy", as shown below.
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
And restore using below function, when you feel the work is done
QApplication::restoreOverrideCursor();
some documentation help:
http://doc.qt.io/qt-5/qguiapplication.html#setOverrideCursor
Now to disable the window, override the event filter function of your window class.
declare a global variable, that says "busy" or "notbusy". ex: _isBusy.
In the event filter do something as shown below.
eventfilter is a virtual function of QObject.
So you can override in your window class as shown below.
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
if (_isBusy) //your global variable to check "busy or "notbusy"
{
//Just bypass key and mouse events
switch(event->type())
{
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
case QEvent::KeyPress:
case QEvent::KeyRelease:
return true;
}
}
}
Note: "MainWindow" in the above function declaration is your class name. Also in the switch statement, I limited the count to only 4 events, add as many events you want.

Related

Triggering an action based on its custom shortcut

Suppose I have some action to happen. For that I can create a QAction object and connect its triggered() signal to the slot that executes the desired function. Also, I can have a shortcut associated with the action; by changing the shortcut I'll be able to execute the same action with that shortcut.
My problem now is that the "shortcut" I wanna set to the action, contains also a mouse button press (and mouse events cannot be assigned to action shortcuts); say I want Shift+Left mouse button. Maybe this sounds a little bit harsh but bear with me.
What do I need? Well, I have a button, and an action (say "execute a script"). I want the script to execute when Shift+Left click is clicked, and I want this "shortcut" to be customized, i.e. the user should be able to change to shortcut to, say Ctrl+Left click (from some GUI element, e.g. button text), and now Ctrl+Left click should execute the script.
How can I achieve this?
Note: I as a user would expect an action triggered by a mouse button to be position dependent. If so, the following gets a bit simpler.
Qt doesn't have an option to specify such a shortcut.
You can roll your own by reacting to mouse events:
Maybe you have an event handler mousePressEvent(),
or a generic eventFilter(QObject *obj, QEvent *evt),
or utilize QApplication::notify
Whichever, at some place you need to catch a QMouseEvent *mouseEvt.
Choose the widget (or qApp) that is as outmost as needed.
There, compare mouseEvt->button() and mouseEvt->modifiers() to your list of actions and trigger the selected action. When the user chooses another trigger method, adjust your list of actions.
Let's put this to practice:
class MainWindow : public QWidget {
Q_OBJECT
public:
QMap<QPair<Qt::MouseButton, Qt::KeyboardModifiers>, QAction*> mapMouseShortcuts;
QAction *pLaunchScript;
MainWindow() : QWidget() {
mapMouseShortcuts.insert(qMakePair(Qt::LeftButton, Qt::ControlModifier), pLaunchScript);
}
void mousePressEvent(QMouseEvent *me) {
QAction *action = mapMouseShortcuts.value(qMakePair(me->button(), me->modifiers()), Q_NULLPTR);
if(action != Q_NULLPTR) {
action->trigger();
me->accept(); // optional
}
// optional:
if(!me->isAccepted()) {
QWidget::mousePressEvent(me);
}
}
};

How to process qt mouse events in parent QWidget first, and then pass it to children?

I have implemented a sort of gestures listener in the parent widget. If the mouse event is a tap ( press and release with out any move events) then the children of that widget should handle the event, if not, and the events describe a swipe, then the parent widget should handle the events. Is there any way to redirect events to the parents first, then rebroadcast them so that the appropriate child could handle it if the need arises.
I think http://qt-project.org/doc/qt-4.8/qobject.html#installEventFilter is what you are looking for. So what you do is that you set any class inheriting from QObject and set it as the event filter. So to quote from the DOCs:
An event filter is an object that receives all events that are sent to this object.
The filter can either stop the event or forward it to this object.
The example in the link is for a QKeyEvent but can obviously be adapted to use various mouse functions as well. Below is a dummy example that would 'eat' the first click on a QPushButton while if you double click, the event would go through as normal (note that in this particular example first you would call the 'eat' sequence and upon the second click in a short time the button would take over).
bool MyWidget::eventFilter(QObject *obj, QEvent *event)
{
if( obj != pushButton ) {
return QObject::eventFilter(obj, event);
}
if (event->type() == QEvent::MouseButtonPress ) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
qDebug("Intercepted mouse click with button %d", mouseEvent->button());
return true;
} else {
// standard event processing
return QObject::eventFilter(obj, event);
}
}
Does this help?

How to detect QTableWidget scroll source (code itself/user (wheel)/user (scrollbar))?

I'm writing a program using Qt 4.8 that displays a table (QTableWidget) filled with filenames and file's params. First an user adds files to the list and then clicks process. The code itself updates the contents of the table with simple progress description. I want the table by default to be scrolled automatically to show the last processed file and that code is ready.
If I want to scroll it by hand the widget is being scrolled automatically as soon as something changes moving the viewport to the last element. I want to be able to override the automated scroll if I detect that it was the user who wanted to change view.
This behavior can be seen in many terminal emulator programs. When there's a new line added the view is scrolled but when user forces the terminal to see some previous lines the terminal does not try to scroll down.
How could I do that?
Solution:
I created an object which filters event processed by my QTableWidget and QScrollBar embedded inside. If I spot the event that should turn off automatic scrolling I just set a flag and stop scrolling view if that flag is set.
Everything is implemented inside tableController class. Here are parts of three crucial methods.
bool tableController::eventFilter(QObject* object, QEvent* event)
{
switch (event->type())
{
case QEvent::KeyPress:
case QEvent::KeyRelease:
case QEvent::Wheel:
case QEvent::MouseButtonDblClick:
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
_autoScrollEnabled = false;
default:
break;
}
return QObject::eventFilter(object, event);
}
void tableController::changeFile(int idx)
{
[...]
if (_autoScrollEnabled)
{
QTableWidgetItem* s = _table.item(_engine.getLastProcessed(), 1);
_table.scrollToItem(s);
}
[...]
}
void tableController::tableController()
{
[...]
_autoScrollEnabled = true;
_table.installEventFilter(this);
_table.verticalTableScrollbar()->installEventFilter(this);
[...]
}
Thanks for all the help. I hope somebody will find it useful :)
Subclass QTableWidget and overload its wheelEvent. You can use the parameters of the supplied QWheelEvent object in order to determine if the user scrolled up or down.
Then use a simple boolean flag which is set (or reset) in your wheelEvent override. The method which is responsible for calling scrollToBottom() should then consider this boolean flag.
You will have to find a way to figure out when to set or reset that flag, e.g. always set it when the user scrolls up and reset it when the user scrolls down and the currently displayed area is at the bottom.
connect(_table->view()->verticalScrollBar(), &QAbstractSlider::actionTriggered, this, [this](int) {
_autoScrollEnabled = false;
});

Close Widget Window if mouse clicked outside of it

This is sort of a chicken and egg problem. I'd like my widget window to be closed when the mouse clicks outside. As I understand it, there will be no mouse events for my widget for a click occurring outside of it. There is a SetFocus slot, but where is its counterpart or focus loss? "focusOutEvent" doesn't get called for my class.
My widget window is a child window of a widget always shown on my main window and it's a "Qt::ToolTip", so I assume some problems could arise from that fact. Any way around that?
My Goal: I have a custom toolbar widget where buttons on it may have “drop down” widgets. These drop down widgets have no standard windows frame. I don’t want them to “steal” caption focus from the main window and I want them to disappear as soon as the user clicks ANYWHERE on the screen outside of their region. I have having serious difficulties finding a strategy that’s not compromise on Qt to get this done.
Am I missing something? (bet I am).
I used:
setWindowFlags(Qt::FramelessWindowHint | Qt::Popup);
This seems to work well on OSX and Windows. My window appears correctly, does not steal the focus from my main window's caption, and the focus loss event is called correctly as soon as I click outside of it.
If your widget could have focus, and 'steal' the caption focus of some of your other widgets, it would have been easier. Something like this could work:
class ToolBarWidget : public QWidget
{
Q_OBJECT
public:
explicit ToolBarWidget(QWidget * parent = 0)
{
setFocusPolicy(Qt::ClickFocus);
}
protected:
void focusOutEvent(QFocusEvent * event)
{
close();
}
}
And when you create any of your widgets you'd do:
ToolBarWidget * pWidget = new ToolBarWidget(this);
pWidget->show();
pWidget->setFocus();
Done! Well, I guess not quiet. first, you don't want the ToolBarWidget to get any focus in the first place. And second, you want for the user to be able to click anywhere and the ToolBarWidget to be hidden.
So, you may keep track of every ToolBarWidget that you create. For example, in a 'QList ttWidgets' member variable. Then, whenever you create a new ToolBarWidget, you'd do this:
ToolBarWidget * pWidget = new ToolBarWidget(this);
pWidget->installEventFilter(this);
pWidget->show();
and in your main widget class, implement the eventFilter() function. Something like:
bool MainWidget::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::FocusOut ||
event->type() == QEvent::KeyPress ||
event->type() == QEvent::MouseButtonPress)
{
while (!ttWidgets.isEmpty()) {
ToolBarWidget * p = ttWidgets->takeFirst();
p->close();
p->deleteLater();
}
}
return MainWidget::eventFilter(obj, event);
}
And that will work. Because this way, even though your ToolTabWidgets aren't getting focus, some other widget in your main widget has focus. And once that changes (whether the user clicked out of your window, or on another control inside it, or in this case, a key or mouse button is pressed, the control will reach that eventFilter() function and close all your tab widgets.
BTW, in order to capture the MouseButtonPress, KeyPress etc. from the other widgets, you would either need to installEventFilter on them too, or just reimplement the QWidget::event(QEvent * event) function in your main widget, and look for those events there.
you can do this by using QDesktopWidget.h like this
void MainWindow::on_actionAbout_triggered()
{
AboutDialog aboutDialog;
//Set location of player in center of display
aboutDialog.move(QApplication::desktop()->screen()->rect().center() -aboutDialog.rect().center());
// Adding popup flags so that dialog closes when it losses focus
aboutDialog.setWindowFlags(Qt::Popup);
//finally opening dialog
aboutDialog.exec();
}
This is what worked for me in order to not steel the focus from the main application:
.h
bool eventFilter(QObject *obj, QEvent *event) override;
.cpp
bool Notification::eventFilter(QObject *obj, QEvent *event)
{
if(event->type() == QEvent::MouseButtonPress)
deleteLater();
return QObject::eventFilter(obj, event);
}
...
// somewhere else (i.e. constructor, main window,...)
qApp->installEventFilter(this);
OP's own answer is great for Qt versions below 4.8, but as they mention in their answer, it does not work for versions above that. The Qt::Popup widget will not disappear when the mouse is clicked outside of the widget, and it will sink all of the input that would normally close it.
Upon further investigation, this is only an issue for non-dialog widgets. A QDialog using Qt::Popup will properly close when the user clicks outside of it, but any other QWidget, like a QFrame, will not. So in order to work around this behavior change in Qt 4.8, all that is necessary is to wrap the widget in a QDialog.

Should I use KeyPressEvent or QAction to implement keypresses?

In Qt, either implementing keyPressEvent or creating a QAction and assigning it a key combination allow me to act based on the keyboard.
Which of these methods is generally preferred?
You should use QAction whenever the same event that is triggered by the key sequence you want may be triggered through other ways like from a menu, toolbar or other buttons. This way you can use the same action on several widgets that should do the same trick.
Excerpt from QAction doc:
The QAction class provides an abstract
user interface action that can be
inserted into widgets.
In applications many common commands
can be invoked via menus, toolbar buttons, and
keyboard shortcuts. Since the user
expects each command to be performed
in the same way, regardless of the
user interface used, it is useful to
represent each command as an action.
I'd prefer to overwrite the keyPressEvent. I don't like the idea of a QAction "lying around somewhere". Just overwrite the keyPressedEvent. I usually do it with a switch-case in which I check the pressed key. Just don't forget to call the keyPressEvent of the base class if you don't want to disable the standard behaviour of a key. Additionally you can check if a "modifier" is pressed while a keyPressEvent occurs. (e.g. Shift or Ctrl). IMHO for general purposes overwriting the keyPressEvent is better than creating invisible, secret actions, unless you want your application to contain all those actions visible for the user.
void my_widget::keyPressEvent( QKeyEvent* p_event )
{
bool ctrl_pressed = false;
if( p_event->modifiers() == Qt::ControlModifier )
{
ctrl_pressed = true;
}
switch( p_event->key() )
{
case Qt::Key_F:
focus_view();
break;
case Qt::Key_I:
if( ctrl_pressed )
{
toggle_interface();
}
else
{
QWidget::keyPressEvent( p_event );
}
break;
case Qt::Key_Return: // return key
case Qt::Key_Enter: // numpad enter key
update_something();
break;
default:
QSpinBox::keyPressEvent( p_event );
}
}
Would depend on what you need it for.
Is it for a menu like action that may be triggered by a menu, button, toolbar too, then go for the QAction. Especially if this action should work all over your program, not only in a single widget.
Is it more like a local activity in a single widget (say for example controlling movement in a game), I would use the keypress event.

Resources