Cannot change cursor in Qt main window from menu action - qt

In my MainWindow, I have a push button and a menu bar item whose signals are both connected to the same slot. In the slot function, I have written:
mainWindow->setCursor(QCursor(Qt::WaitCursor));
This works as expected when the slot function is invoked via the button; however, when the same function is invoked from the menu, the wait cursor doesn't appear. Any idea why?
I also considered using QApplication::setOverrideCursor; however, that causes other problems.
Any recommendations? Thanks!
(I am using Qt 4.7 and doing my development on Windows 7 using Qt Creator with the default MinGW compiler.)
Here's more detail.
in MainWindow constructor: this->setCursor(Qt::CrossCursor);
signal/slot connections:
QObject::connect(button, SIGNAL(clicked()), MainWindow, SLOT(showMessageBox()));
QObject::connect(action, SIGNAL(triggered()), MainWindow, SLOT(showMessageBox()));
showMessageBox function:
void MainWindow::showMessageBox()
{
this->setCursor(Qt::WaitCursor);
// display wait cursor briefly before showing message box
for (int i = 0; i < 1<<30; ) {++i;}
QMessageBox msgBox;
msgBox.setText("Hello!");
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setCursor(Qt::PointingHandCursor);
msgBox.exec();
this->setCursor(Qt::CrossCursor);
}
When showMessageBox is invoked with 'button', the wait cursor is displayed as expected.
When showMessageBox is invoked through 'action', the wait cursor does not appear; instead the cursor changes from Qt::CrossCursor to a Qt::ArrowCursor as soon as the user selects the 'action' menu item, and then changes to Qt::PointingHandCursor once the message box opens. The wait cursor never appears.

Your code is synchronous and uses a delay loop. When you're in the delay loop, there's no way for any Qt code to execute. A cursor change requires the event loop to be spinning -- so it appears from the symptoms you give.
Here's how to do it correctly -- remember, if you use delays/sleeps and other blocking calls in your GUI code, your users will hate you, and rightly so. Using exec() in message/dialog boxes is also bad style. Your application is asynchronous, code it so. Make sure your slots are declared as such (in the protected slots: section of MainWindow declaration).
void MainWindow::showMessageBox()
{
this->setCursor(Qt::WaitCursor);
QTimer::singleSlot(200, this, SLOT(slot1()); // fire slot1 after 200ms
}
void MainWindow::slot1()
{
QMessageBox * msgBox = new QMessageBox(this);
msgBox->setText("Hello!");
msgBox->setStandardButtons(QMessageBox::Ok);
msgBox->setCursor(Qt::PointingHandCursor);
msgBox->show();
connect(msgBox, buttonClicked(QAbstractButton*), SLOT(slot2(QAbstractButton*)));
}
void MainWindow::slot2(QAbstractButton* button)
{
// a button was clicked on the message box
this->setCursor(Qt::CrossCursor);
}

Related

QT , my form was hidden after calling setWindowFlags() in my slots

I just want to disable form's close button while doing a task(by QThread), So I connected the thread's signal "started()" and "finished()" to my two slots, for controlling my form's close button.
//...
m_pTestThread = new TestThread();
connect(m_pTestThread, SIGNAL(started()), this, SLOT(onThreadStart()));
connect(m_pTestThread, SIGNAL(finished()), this, SLOT(onThreadFinish()));
m_pTestThread->start();
//...
void QTest::onThreadStart()
{
this->setWindowFlags(this->windowFlags() & (~Qt::WindowCloseButtonHint));
}
void QTest::onThreadFinish()
{
this->setWindowFlags(this->windowFlags() | Qt::WindowCloseButtonHint);
}
After the thread started, my form was hidden... that is strange.
So I call show() after setWindowFlags() function to avoid this problem,
but still don't know why this happened...
Is this the expected behaviour? Should I call show() after setWindowFlags()?
Check the documentation for setWindowFlags here:
Note: This function calls setParent() when changing the flags for a
window, causing the widget to be hidden. You must call show() to make
the widget visible again..

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);
}
}
};

In QDialogButtonBox, where does it disconnect on-destroy connection of buttons when dialog closed?

I want to build something like QMessageBox but with my own style and layout. So I am tracing qt's source code and learn from it.
QMessageBox is composed with some label widgets as content and QDialogButtonBox as buttons.
int ret = QMessageBox::warning(nullptr, QString("My Application"),
QString("Dialog content"),
QMessageBox::Save | QMessageBox::Cancel,
QMessageBox::Save)
The code snippet above build a simple QMessageBox with two buttons save and cancel.
In source code, qt will add button with two connection clicked and destroyed in qdialogbuttonbox.cpp
void QDialogButtonBoxPrivate::addButton(QAbstractButton *button,
QDialogButtonBox::ButtonRole role,
bool doLayout)
{
Q_Q(QDialogButtonBox);
QObject::connect(button, SIGNAL(clicked()), q, SLOT(_q_handleButtonClicked()));
QObject::connect(button, SIGNAL(destroyed()), q, SLOT(_q_handleButtonDestroyed()));
buttonLists[role].append(button);
if (doLayout)
layoutButtons();
}
When clicking Cancel buttons in a QMessageBox, it will run:
q->done(execReturnCode(button)); // does not trigger closeEvent
in qmessgebox.cpp and return from event loop and destroy the QMessageBox instance.
In my understanding, all buttons will also be destroyed when QMessageBox is destroyed, so it should trigger _q_handleButtonDestroyed handler and cause some weird behavior.
I set some breakpoints in IDE and run. It doesn't step into _q_handleButtonDestroyed on clicking buttons. It also doesn't step into all disconnection in line #663 and #726 of qdialogbuttonbox.cpp
I want to know where does it disconnect the _q_handleButtonDestroyed connection when clicking button? Or is there anything I got wrong?
Thanks in advance.

speeding up initial display of contextMenu?

Environment: Qt 5.1 OSX 10.7.5
I am showing a contextMenu when a Qt::RightButton event is received.
Issue: It works fine except that the initial display is very slow and can take 3-5 seconds to display the menu. Any subsequent displays are immediate. The delay is long enough so that the user can think nothing is happening.
Question: Is there any way to preload or otherwise speed up the initial display of the contextMenu?
I've tried initializing it in my class constructor:
contextMenu = new QMenu(this);
QAction *saveAction=contextMenu->addAction("Save");
connect(saveAction,SIGNAL(triggered()),this,SLOT(saveSlot()));
I've tried declaring it as a pointer and as a... (not pointer? ;-)
QMenu *contextMenu;
This is the mousePressEvent that executes to show the contextMenu.
void RPImageLabel::mousePressEvent(QMouseEvent *event)
{
if (!imageRect.contains(event->pos())) return;
origin = event->pos();
this->setFocus();
if (event->button()==Qt::RightButton){
if (selectionRect.contains(origin))
// contextMenu.exec(this->mapToGlobal(origin));
contextMenu->exec(this->mapToGlobal(origin));
} else {
selectionStarted=true;
selectionRect.setTopLeft(origin);
selectionRect.setBottomRight(origin);
if (rubberBand->isHidden()){
rubberBand->setGeometry(QRect(origin, origin));
rubberBand->show();
repaint();
}
}
}
Ok, I solved this by changing the contextMenuPolicy from DefaultContextMenu to ActionsContextMenu for the widget in Qt Creator.
I'm new to Qt so just guessing here but perhaps this uses a Qt contextMenu instead of the OSX menu? In any event, it displays immediately now. However it does throw an alert on certain conditions:
QNSView mouseDragged:
Internal mouse button tracking invalid (missing Qt::LeftButton)
Not clear what is going on but I see that there has been a bug report filed which may be related.

Qt Menu with QLinEdit action

I want to have a line edit field in a popup menu I've got. I'm basically letting the user pick from one of several common sizes for something, but I want them to be able to enter a custom size as the last entry in the menu.
So I've got something like this (snipped from larger code, new_menu is the menu of interest):
QWidget *widget = new QWidget(new_menu);
QHBoxLayout *layout = new QHBoxLayout;
QLineEdit* le = new QLineEdit;
le->setPlaceholderText("Custom");
le->setFixedWidth(100);
ayout->addWidget(le);
widget->setLayout(layout);
QWidgetAction* wa = new QWidgetAction(new_menu);
wa->setActionGroup(group);
wa->setDefaultWidget(widget);
new_menu->addAction(wa);
connect(le, SIGNAL(returnPressed()), this, SLOT(leslot()));
Which works great, the LineEdit shows up nice and centered in the menu, it's got the placeholder text, I can click it and edit, everything. However, when I hit enter on the textBox, it emits the returnPressed signal and the menu emits a triggered signal with one of the other actions on the list, so at best I'm changing my configuration twice and at worst things break.
Additionally, when I click off the edge of the LineEdit (still in the menu though, but not in the editable area), the menu emits a triggered signal with the QWidgetAction associated with it, which isn't what I want.
So two questions:
1) Can I get the return to work the way I want. It's fine if the menu closes when it's hit, but it can't emit another action too.
2) Can I get it to not emit an action at all when the lineEdit is clicked?
Here's what I ended up doing for anyone that follows. I subclassed QLineEdit thusly:
class EnterLineEdit : public QLineEdit {
Q_OBJECT
public:
void keyPressEvent(QKeyEvent *evt) {
if (evt->key() == Qt::Key_Enter || evt->key() == Qt::Key_Return) {
emit returnPressed();
} else {
QLineEdit::keyPressEvent(evt);
}
}
};
This lets me manually emit the returnPressed signal when enter/return is hit and not pass it up the widget hierarchy, so the menu never sees it when enter is hit over the lineedit. I connected the returnPressed signal to the hide() slot of the menu so that the menu will still close, but without triggering an action.

Resources