I reimplement keyPressEvent function in my widget.
I want to disable key press while doing some works in keyPressEvent function like this:
void TrackingForm::keyPressEvent(QKeyEvent *event)
{
// disable get keyPress
doWork();
// enable
}
the other way is clear buffer of events posted (queueded events). I use QApplication::removePostedEvents in keyPressEvent function but it does not work:
void TrackingForm::keyPressEvent(QKeyEvent *event)
{
doWork(); // this function takes about 3 seconds
QApplication::removePostedEvents(this);
}
Can someone help me?
thanks a lot
You could try to execute doWork() in a separate thread - then you could just ignore events in keyPressEvent() while doWork() is running...
For example you could try this:
void TrackingForm::keyPressEvent(QKeyEvent *event)
{
if (!workInProgress) //workInProgress is a bool member
QtConcurrent::run(doWork);
//doWork() sets workInProgress to true before work,
//and to false after work is done
else
event->ignore();
}
Related
I've subclassed Qt QAbstractSpinBox to create ComplexSpinBox that handles complex numbers.
To do this, I'm overriding keyPressEvent(), mousePressEvent(), and wheelEvent() and if the keyboard Ctrl modifier is active then the imaginary portion of the complex number is incremented or decremented. Otherwise the real portion is updated. (Also including a custom validator for complex numbers.)
All is cool except that holding the up and down arrow buttons down doesn't make them repeat.
What am I leaving out?
Well, one, if not the way to do this is to add
private:
QTimer *timer;
in the definition and create it in the constructor:
timer = new QTimer(this);
connect (timer, &QTimer::timeout,
[=]() {
// do your thing
});
Then somewhere in the mousePressEvent(QMouseEvent *mouseEvent) method
timer->start (100);
For reasons that aren't clear to me, mouseReleaseEvent() doesn't get triggered in this environment so you have to use an event filter. Back in the definition, you'll need:
protected:
bool eventFilter(QObject *object, QEvent *event);
and the method
bool ComplexSpinBox::eventFilter(QObject *object, QEvent *event)
{
if (object == this && event->type() == QEvent::MouseButtonRelease) {
timer->stop ();
}
return false;
}
I faced an error and I didn't found any solutions for this problem. So I have made a subclass from QLineEdit, and overrided a keyPressEvent method. Now if I try to write something it doesn't allow it, but it triggers the event. Any advices?
.h
class PlayerQLineEdit : public QLineEdit
{
public:
PlayerQLineEdit();
void keyPressEvent(QKeyEvent *);
};
.cpp
PlayerQLineEdit::PlayerQLineEdit()
{
setDisabled(false);
}
void PlayerQLineEdit::keyPressEvent(QKeyEvent *)
{
}
You have to call the base class event handler. Otherwise the line edit can't get any key presses!
void PlayerQLineEdit::keyPressEvent(QKeyEvent *event)
{
// ... do stuff
// optionally return before calling base class handler to suppress key strokes.
QLineEdit::keyPressEvent(event);
// ... do stuff
}
I have several fields in a widget, that each can affect the behavior of an item, and changing some of them will change others.
I read somewhere that the editingFinished() signal of a line edit is triggered only by user actions - and not by code changes... Is that true ?
connect(m_lineEdit1, SIGNAL(editingFinished()), this, SLOT(m_lineEdit1Changed()));
connect(m_lineEdit2, SIGNAL(editingFinished()), this, SLOT(m_lineEdit2Changed()));
connect(this, SIGNAL(someSignal()), this, SLOT(updateData()));
void m_lineEdit1Changed()
{
changedata1();
emit someSignal();
}
void m_lineEdit2Changed()
{
changedata2();
emit someSignal();
}
void updateData()
{
m_lineEdit1.setText(fromdata);
m_lineEdit2.setText(fromdata);
}
If I change m_lineEdit1, and update the entire widget (which changes, through code, m_lineEdit2), I hit a breakpoint in m_lineEdit2Changed()
This leads to an infinite loop of updates...
What can I do to get around it ?
Blocking signals is a bit of a sledgehammer of an approach. You can use a sentinel class to explicitly prevent recursion:
#define SENTINEL_STRINGIFY(x) #x
#define SENTINEL_TOSTRING(x) SENTINEL_STRINGIFY(x)
#define SENTINEL_AT __FILE__ ":" SENTINEL_TOSTRING(__LINE__)
class Sentinel {
Q_DISABLE_COPY(Sentinel);
static QMutex m_mutex;
static QSet<QString> m_sentinels;
QString const m_sentinel;
bool const m_ok;
static bool checkAndSet(const QString & sentinel) {
QMutexLocker lock(&m_mutex);
if (m_sentinels.contains(sentinel)) return false;
m_sentinels.insert(sentinel);
return true;
}
public:
explicit Sentinel(const char * sentinel) :
m_sentinel(sentinel), m_ok(checkAndSet(m_sentinel)) {}
~Sentinel() {
if (!m_ok) return;
QMutexLocker lock(&m_mutex);
m_sentinels.remove(m_sentinel);
}
bool operator()() const { return m_ok; }
};
QMutex Sentinel::m_mutex;
QSet<QString> Sentinel::m_sentinels;
...
void Foo::m_lineEdit1Changed()
{
Sentinel s(SENTINEL_AT);
if (!s) return; // exit if this method is on the call stack
...
changedata1();
emit someSignal();
}
This is thread-safe and can be used from any thread.
A technique to avoid this problem is to use the QObject::blockSignals() function.
In your example you would do:
void updateData()
{
m_lineEdit1.blockSignals(true);
m_lineEdit1.setText(fromdata);
m_lineEdit1.setText(fromdata);
m_lineEdit1.blockSignals(false);
}
The blockSignals() call prevents the object sending any signals while you are changing the data in the line edit.
For example, consider a main menu item that has the Delete key as a shortcut (with Qt::WindowShortcut as context). I want another QWidget to handle the Delete key when focused. This is not possible because the Delete key is processed by the main menu. I've tried grabbing the keyboard on QWidget focus but that doesn't do anything. Is this event possible?
I was able to get the behavior I wanted by installing an event filter on qApp when the QWidget is focused (remove it when losing focus), and returning true for all QEvent::Shortcut types.
void MyWidget::focusInEvent( QFocusEvent *event )
{
qApp->installEventFilter(this);
}
void MyWidget::focusOutEvent( QFocusEvent *event )
{
qApp->removeEventFilter(this);
}
bool MyWidget::eventFilter( QObject *target, QEvent *event )
{
if (event->type() == QEvent::Shortcut)
{
// If I care about this shortcut, then return true to intercept
// Else, return false to let the application process it
}
return false;
}
If there's a better way, I'd love to hear it!
Is there a signal that tells when 'show' function finishes?
I have a problem in my code: If I write:
QMainWinObj.show();
QMainWinObj.someGuiFunc();
the code doesn't work. But, if I write:
QMainWinObj.show();
sleep(3000);
QMainWinObj.someGuiFunc();
It does.
So I think the problem is that 'show' dosn't finish its jub before I call 'someGuiFunc'. That's why I want to have some kind of a sign that 'show' is finished..
This may be a bit dated but since nobody else answered it except the one:
Since there is no "Show" signal I suggest overriding the show event like this:
In your mainwindow.cpp file:
void MainWindow::show()
{
QMainWindow::show();
QApplication::processEvents();
emit windowShown();
}
In your mainwindow.h file, somewhere in MainWindow's declaration:
...
class MainWindow: public QMainWindow
{
...
signals:
void windowShown();
...
}
...
Then, when you go to the designer, right click on the main window (very top of the object tree), and select "Change signals/slots". In the "Signals" frame, click the "+" button, and you will need to add "windowShown()" and then press enter, and then the OK button (note that the elipses "..." denote other code that is already in your header).
That's it -- you can now use the signals/slots editor to link slots up to the 'windowShown' signal whenever you want. Now if you want something more like Microsoft's "Loaded" event which I think is used in .NET you will need to create some instance variable and flag it so that every time the window is shown, it isnt emitted, for example:
void MainWindow::show()
{
QMainWindow::show();
QApplication::processEvents();
emit windowShown();
if (firstTimeShown == true)
{
emit windowLoaded();
firstTimeShown = false;
}
}
Also, don't forget to initialize the variable to 'true' in your constructor:
MainWindow::MainWindow(QObject* parent)
...
{
firstTimeShown = true; // put this somewhere before ui->setupUi()
}
If you decide to put it in the initializer list however, make sure it is in proper order. The compiler will complain if the variables are not instantiated in a top-to-bottom fashion as declared in the class' header.
Now, make sure when you define firstTimeShown in your header, that you make it private. And lets not forget the added signals:
class MainWindow : public QMainWindow
{
...
signals:
void windowLoaded();
void windowShown();
private:
bool firstTimeShown;
...
That's about it. With the flexibility of signals and slots, its pretty easy to mimic any event that you might find from windows forms or from MFC. It just takes a little effort on the programmer's part. Once you get the hang of it however it it'll be like second nature.
note: there probably are optimizations or better and more precise ways of making the "Loaded" and "Shown" signals perform but I have left things like this out for simplicity's sake. And to come back to the question at hand, calling QApplication::processEvents() is most likely what you want to do instead of waiting a fixed amount of time because who knows how long it will take if the user is running 100 other things on top of it, etc, etc. Hope that helped, the extra explanation was included hoping that it might give you a better way to do the things that you want to do instead of waiting for something to be done, 'knowing' it is done is a much better alternative.
There is no such signal, but having QMainWindow subclassed you can override showEvent event.
void MainWindow::showEvent(QShowEvent *){
//your code
}
More info here: http://qt-project.org/doc/qt-4.8/qwidget.html#showEvent
Be aware it's called every time your window is about to be displayed.
Problem can decide without subclassing, just installing event filter like this:
class CWidgetIsPainting_EF : public QObject
{
bool m_bIsPainted = false;
public:
CWidgetIsPainting_EF( QObject * parent = 0 ) : QObject (parent) { }
inline bool IsPainted() const { return m_bIsPainted; }
inline void setIsPainted( bool bIsPainted ) { m_bIsPainted = bIsPainted; }
protected:
bool eventFilter( QObject * obj, QEvent *event )
{
if (event->type() == QEvent::Paint)
{
m_bIsPainted = true;
return true;
};
return QObject::eventFilter(obj, event);
}
};
...
...
CWidgetIsPainting_EF * pPaintingEF = new CWidgetIsPainting_EF( m_pWidget );
m_pWidget->installEventFilter( pPaintingEF );
...
...
while ( !pPaintingEF->IsPainted() )
QApplication::processEvents();
Override bool event(QEvent *event) and catch the Paint event. Works for me at least on Windows.
// MainWindow.h
class MainWindow : public QMainWindow
{
...
bool event(QEvent *event) override;
void functionAfterShown();
...
bool functionAfterShownCalled = false;
...
}
// MainWindow.cpp
bool MainWindow::event(QEvent *event)
{
const bool ret_val = QMainWindow::event(event);
if(!functionAfterShownCalled && event->type() == QEvent::Paint)
{
functionAfterShown();
functionAfterShownCalled = true;
}
return ret_val;
}