QLineEdit: Set cursor location to beginning on focus - c++

I have a QLineEdit with an input mask, so that some kind of code can easily be entered (or pasted). Since you can place the cursor anywhere in the QLineEdit even if there is no text (because there is a placeholder from the input mask):
If people are careless and unattentive enough this leads to them typing in the middle of the text box whereas they should start typing at the beginning. I tried the trivial way of ensuring that the cursor is at the start upon focus by installing an event filter:
bool MyWindowPrivate::eventFilter(QObject * object, QEvent * event)
{
if (object == ui.tbFoo && event->type() == QEvent::FocusIn) {
ui.tbFoo->setCursorPosition(0);
}
return false;
}
This works fine with keybaord focus, i.e. when pressing ⇆ or ⇧+⇆, but when clicking with the mouse the cursor always ends up where I clicked. My guess would be that QLineEdit sets the cursor position upon click itself after it got focus, thereby undoing my position change.
Digging a little deeper, the following events are raised when clicking¹ and thus changing focus, in that order:
FocusIn
MouseButtonPress
MouseButtonRelease
I can't exactly catch mouse clicks in the event filter, so is there a good method of setting the cursor position to start only when the control is being focused (whether by mouse or keyboard)?
¹ Side note: I hate that Qt has no documentation whatsoever about signal/event orders for common scenarios such as this.

Below is an implementation that's factored into a separate class. It defers the setting of the cursor to after any pending events are posted for the object, thus sidestepping the issue of event order.
#include <QApplication>
#include <QLineEdit>
#include <QFormLayout>
#include <QMetaObject>
// Note: A helpful implementation of
// QDebug operator<<(QDebug str, const QEvent * ev)
// is given in http://stackoverflow.com/q/22535469/1329652
/// Returns a cursor to zero position on a QLineEdit on focus-in.
class ReturnOnFocus : public QObject {
Q_OBJECT
/// Catches FocusIn events on the target line edit, and appends a call
/// to resetCursor at the end of the event queue.
bool eventFilter(QObject * obj, QEvent * ev) {
QLineEdit * w = qobject_cast<QLineEdit*>(obj);
// w is nullptr if the object isn't a QLineEdit
if (w && ev->type() == QEvent::FocusIn) {
QMetaObject::invokeMethod(this, "resetCursor",
Qt::QueuedConnection, Q_ARG(QWidget*, w));
}
// A base QObject is free to be an event filter itself
return QObject::eventFilter(obj, ev);
}
// Q_INVOKABLE is invokable, but is not a slot
/// Resets the cursor position of a given widget.
/// The widget must be a line edit.
Q_INVOKABLE void resetCursor(QWidget * w) {
static_cast<QLineEdit*>(w)->setCursorPosition(0);
}
public:
ReturnOnFocus(QObject * parent = 0) : QObject(parent) {}
/// Installs the reset functionality on a given line edit
void installOn(QLineEdit * ed) { ed->installEventFilter(this); }
};
class Ui : public QWidget {
QFormLayout m_layout;
QLineEdit m_maskedLine, m_line;
ReturnOnFocus m_return;
public:
Ui() : m_layout(this) {
m_layout.addRow(&m_maskedLine);
m_layout.addRow(&m_line);
m_maskedLine.setInputMask("NNNN-NNNN-NNNN-NNNN");
m_return.installOn(&m_maskedLine);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Ui ui;
ui.show();
return a.exec();
}
#include "main.moc"

You could use a QTimer in focusInEvent to call a slot that sets the cursor position to 0.
This works well because a single shot timer posts a timer event at the end of the object's event queue. A mouse-originating focus-in event necessarily has the mouse clicks already posted to the event queue. Thus you're guaranteed that the timer's event (and the resulting slot call) will be invoked after any lingering mouse press events.
void LineEdit::focusInEvent(QFocusEvent *e)
{
QLineEdit::focusInEvent(e);
QTimer::singleShot(0, this, SLOT(resetCursorPos()));
}
void LineEdit::resetCursorPos()
{
setCursorPosition(0);
}

set a validator instead of inputmask .
http://doc.qt.io/qt-5/qregularexpressionvalidator.html

Related

How to get mouse coordinates with C + + QT?

void Window::acquire(QMouseEvent * event)
{
pos_xy->setText(QString("coordinates:(%1,%2)").arg(event->pos().x()).arg(event->pos().y()));
}
Window is the inheritance class of QWidget, and the above code is a member function of this class。pos_xy is a QLineEdit *.
i want to get the coordinates of the mouse click,but i don't know how to call the acquire function when the mouse clicked.
Thanks in advance!
If you want to be notified whenever the user clicks anywhere inside the window, you can implement that behavior using an event filter. For example, you could create a class like this:
#include <QObject>
#include <QMouseEvent>
class MouseWatcher : public QObject
{
public:
MouseWatcher(QWidget * parent) : QObject(parent) {/* empty */}
virtual bool eventFilter(QObject * obj, QEvent * event)
{
if (event->type() == QEvent::MouseButtonPress)
{
QMouseEvent * me = static_cast<QMouseEvent *>(event);
QPointF windowPos = me->windowPos();
printf("User clicked mouse at %f,%f\n", windowPos.x(), windowPos.y());
}
return QObject::eventFilter(obj, event);
}
};
... and then install it as a filter on your window object, like this:
MyWindowObject * win = [...];
MouseWatcher * mw = new MouseWatcher(win);
win->installEventFilter(mw);
... and now it will print the window-relative mouse co-ordinates to stdout every time the user clicks on the window.

Qt - Why can't I trigger mousePressEvent for my custom button in MainWindow

This is my first time to ask on Stack Overflow. If any suggestion about asking question, please let me know.
I am very new to Qt, and have some problems while using event. Hope someone can provide any thoughts.
Background:
I have my custom pushButton, which is rxPushButton in rx.h and rx.cpp. I use on_rxPushButton_clicked to change the image and it works pretty well.
In MainWindow, I need to use some rx so I include the class rx and I want to detect if I press left button of the mouse, I need to know which rx has been pressed and record its id in int rxId in MainWindow.
Problem:
I tried two ways to achieve my goal, including mousePressEvent and eventFilter. I found that I can't detect the mouse pressed signal on any rx, but I can detect it outside rx in other places in Mainwindow. I wonder if the events will conflict, but when I comment on_rxPushButton_clicked in rx.cpp, MainWindow still doesn't work for the problem. So I presume that maybe the space in the screen occupied by rx will not be in control of MainWindow (I can get Debug message "test1" but not "test2" in my code, check below).
How should I do to solve this problem if I need both things (change image in rx and modify one variable in MainWindow)? Or maybe it's just something wrong with my code and how to modify?
I hope to separate them if possible because I still need to include many objects in MainWindow in the future.
Here are some of my related codes:
rx.cpp
void rx::on_rxPushButton_clicked(void)
{
startLoading();
}
void rx::startLoading(void)
{
state = 1;
connect(timer, SIGNAL(timeout()), this, SLOT(loading1()));
timer->start(LOADING_INTERVAL);
}
void rx::loading1(void)
{
if(state == 1)
{
state = 2;
ui->rxPushButton->setStyleSheet("border-image: url(:/images/Rx/Rxloading1.png);");
disconnect(timer, SIGNAL(timeout()), this, SLOT(loading1()));
}
}
mainwindow.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
for(int i = 0 ; i < rxSize ; i++)
{
rxList << new rx(this);
int j = i/rxHorizontalCount;
rxList[i]->setGeometry(500+(i-j*8)*110,10+j*90,100,90);
}
//rxList[0]->installEventFilter(this);
}
void MainWindow::mousePressEvent(QMouseEvent *event)
{
if(event->buttons() & Qt::LeftButton)
{
qDebug() << "test1";
if(rxList[0]->rect().contains(event->x(), event->y()))
qDebug() << "test2";
}
}
Change image in rx
Use QSignalMapper class that bundles signals from QWidgets (class rx) and re-emits them with widget (class rx) parameters corresponding to the object that sent the signal.
We connect each button's clicked() signal to the signal mapper's map() slot, and create a mapping in the signal mapper from each button to the button itself.
Finally we connect the signal mapper's mapped() signal to the custom widget's(rx object) clicked() signal. When the user clicks a button, the custom widget(rx object) will emit a single clicked() signal whose argument is the button (rx object) the user clicked.
Handle the button clicked event in MainWindow::slotButtonsClicked(QWidget *p) function.
Modify n variable in MainWindow:
You can update variable of MainWindow in mousePressEvent function
class MainWindow : public QWidget
{
public :
MainWindow (QWidget *parent);
QSignalMapper * mapper;
slots:
void slotButtonsClicked(QWidget *);
// ...
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
mapper = new QSignalMapper(this);
for(int i = 0 ; i < rxSize ; i++)
{
rxList << new rx(this);
int j = i/rxHorizontalCount;
rxList[i]->setGeometry(500+(i-j*8)*110,10+j*90,100,90);
QObject::connect(rxList[i], SIGNAL(clicked()),mapper,SLOT(map()));
//Adds a mapping so that when map() is signalled from the sender, the signal mapped(widget ) is emitted.
mapper->setMapping(rxList[i], rxList[i]);
}
QObject::connect(mapper,SIGNAL(mapped(QWidget *)),this,SLOT(slotButtonsClicked(QWidget *)));
}
void MainWindow::mousePressEvent(QMouseEvent *event)
{
if(event->buttons() & Qt::LeftButton)
{
qDebug() << "Clicked outside the button";
//Now you can modify n variable in MainWindow
}
MainWindow::mousePressEvent(event);
}
void MainWindow::slotButtonsClicked(QWidget *p)
{
rx *button = dynamic_cast<rx *>(p);
button->on_rxPushButton_clicked();
qDebug() << button <<" clicked on button";
//Now you can change image in rx
}
Hope this works :)
Event propagating prevent you to do it. When mouse is over Button, event sends to button, not to the MainWindow, thats why you never see test2 in debug output.
Since I don't know what do you need it's hard to say what you should do. You can process event in Button and send some signals or whatever, or set event filter and check if target object is your button, and so on.
Any way, read Qt event system docs for better understanding.

A lot of widgets seems to have default behavior for the space bar key press event. How can I override this without subclassing every widget?

I have a very specific piece of code that needs to be executed instantly, no matter what else is going on in the gui, when the space bar is pressed. I have the following snippet of code in each of my keypress event filters:
else if(keyPressed == Qt::Key_Space){
emit sigHalted();
}
This works fine, unless certain widgets have focus. The ones causing me issues are:
QTableWidget
QPushButton
If I'm editing an in a QTableWidget, and I hit space bar, then it adds a space bar to the item in the QTableWidget instead of executing the code above. If I click a button with the mouse, and then hit space bar, it acts as if I clicked that same button again instead of executing the code above.
I know I can fix this behavior by subclassing the widgets and overriding their event filters, but I would prefer to avoid this, because I have a lot of buttons and tables and I would have to go through and replace all of them with the new, subclassed versions. Is there a way I can catch the space bar keypress event before it goes to the widget's default behavior?
You must use eventFilter.
Enable the event:
code:
#include <QApplication>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
qApp->installEventFilter(this);
}
Declare the function:
code:
bool eventFilter(QObject *watched, QEvent *event);
Override the function:
code:
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
if (event->type() == QEvent::KeyPress){
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
if (keyEvent->key() == Qt::Key_Escape){
//your code here
emit sigHalted();
return true;
}
else{
return false;
}
}
else
return QMainWindow::eventFilter(watched,event);
}

My Qt eventFilter() doesn't stop events as it should

Something is fundamentally wrong with my eventFilter, as it lets every single event through, while I want to stop everything. I've read lots of documentation on QEvent, eventFilter() and so on, but obviously I'm missing something big. Essentially, I'm trying to create my own modal-functionality for my popup-window class based on QDialog. I want to implement my own since the built-in setModal(true) includes a lot of features, e.g. playing QApplication::Beep(), that I want to exclude. Basically, I want to discard all events going to the QWidget (window) that created my popup. What I have so far is,
// popupdialog.h
#ifndef POPUPDIALOG_H
#define POPUPDIALOG_H
#include <QDialog>
#include <QString>
namespace Ui {class PopupDialog;}
class PopupDialog : public QDialog
{
Q_OBJECT
public:
explicit PopupDialog(QWidget *window=0, QString messageText="");
~PopupDialog();
private:
Ui::PopupDialog *ui;
QString messageText;
QWidget window; // the window that caused/created the popup
void mouseReleaseEvent(QMouseEvent*); // popup closes when clicked on
bool eventFilter(QObject *, QEvent*);
};
...
// popupdialog.cpp
#include "popupdialog.h"
#include "ui_popupdialog.h"
PopupDialog::PopupDialog(QWidget *window, QString messageText) :
QDialog(NULL), // parentless
ui(new Ui::PopupDialog),
messageText(messageText),
window(window)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose, true); // Prevents memory leak
setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
ui->message_text_display->setText(messageText);
window->installEventFilter(this);
//this->installEventFilter(window); // tried this also, just to be sure ..
}
PopupDialog::~PopupDialog()
{
window->removeEventFilter(this);
delete ui;
}
// popup closes when clicked on
void PopupDialog::mouseReleaseEvent(QMouseEvent *e)
{
close();
}
Here's the problem, the filter doesn't work. Note that if I write a std::cout
inside the if(...), I see that it does trigger whenever events are sent to window, it just doesn't stop them.
bool PopupDialog::eventFilter(QObject *obj, QEvent *e)
{
if( obj == window )
return true; //should discard the signal (?)
else
return false; // I tried setting this to 'true' also without success
}
When the user interacts with the main program, a PopupDialog can be created like this:
PopupDialog *popup_msg = new PopupDialog(ptr_to_source_window, "some text message");
popup_msg->show();
// I understand that naming the source 'window' might be a little confusing.
// I apologise for that. The source can in fact be any 'QWidget'.
Everything else works as expected. Only the event filter fails. I want the filter to remove events sent to the window that created the popup; like mouse clicking and key pressing, until the popup is closed. I'm expecting to be extremely embarrassed when someone points out a trivial fix in my code.
You have to ignore all events that arrive in the widget tree of the window. Therefore, you need to install the eventFilter application-wide and check, if the object you are filtering on is a descendant of window. In other words: Replace
window->installEventFilter(this);
by
QCoreApplication::instance()->installEventFilter(this);
and implement the event filter function this way:
bool PopupDialog::eventFilter(QObject *obj, QEvent *e)
{
if ( !dynamic_cast<QInputEvent*>( event ) )
return false;
while ( obj != NULL )
{
if( obj == window )
return true;
obj = obj->parent();
}
return false;
}
I tried it, tested it and it worked for me.
Note: Using event filters in Qt is a bit messy in my experience, since it is not quite transparent what is happening. Expect bugs to pop up from time to time. You may consider disabling the main window instead, if you and your clients don't have a problem with the grayed-out main window as a consequence.
After the massive amount of responses, feedback, suggestions and time ivested in extensive research I've finally found what I believe to be the optimal, and safest solution. I wish to express my sincere gratidtude to everyone for their aid to what Kuba Ober describes as "(...) not as simple of a problem as you think".
We want to filter out all certain events from a widget, including its children. This is difficult, because events may be caught in the childrens default eventfilters and responded to, before they are caught and filtered by the the parent's custom filter for which the programmer implements. The following code solves this problem by installing the filter on all children upon their creation. This example assumes the use of Qt Creator UI-forms and is based on the following blog post: How to install eventfilters for all children.
// The widget class (based on QMainWindow, but could be anything) for
// which you want to install the event filter on, includings its children
class WidgetClassToBeFiltered : public QMainWindow
{
Q_OBJECT
public:
explicit WidgetClassToBeFiltered(QWidget *parent = 0);
~WidgetClassToBeFiltered();
private:
bool eventFilter(QObject*, QEvent*);
Ui::WidgetClassToBeFiltered *ui;
};
...
WidgetClassToBeFiltered::WidgetClassToBeFiltered(QWidget *parent) :
QMainWindow(parent), // Base Class constructor
ui(new Ui::WidgetClassToBeFiltered)
{
installEventFilter(this); // install filter BEFORE setupUI.
ui->setupUi(this);
}
...
bool WidgetClassToBeFiltered::eventFilter(QObject *obj, QEvent* e)
{
if( e->type() == QEvent::ChildAdded ) // install eventfilter on children
{
QChildEvent *ce = static_cast<QChildEvent*>(e);
ce->child()->installEventFilter(this);
}
else if( e->type() == QEvent::ChildRemoved ) // remove eventfilter from children
{
QChildEvent *ce = static_cast<QChildEvent*>(e);
ce->child()->removeEventFilter(this);
}
else if( (e->type() == QEvent::MouseButtonRelease) ) // e.g. filter out Mouse Buttons Relases
{
// do whatever ..
return true; // filter these events out
}
return QWidget::eventFilter( obj, e ); // apply default filter
}
Note that this works, because the eventfilter installs itself on added children! Hence, it should also work without the use of UI-forms.
Refer this code to filter out specific event:-
class MainWindow : public QMainWindow
{
public:
MainWindow();
protected:
bool eventFilter(QObject *obj, QEvent *ev);
private:
QTextEdit *textEdit;
};
MainWindow::MainWindow()
{
textEdit = new QTextEdit;
setCentralWidget(textEdit);
textEdit->installEventFilter(this);
}
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
if (obj == textEdit) {
if (event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
qDebug() << "Ate key press" << keyEvent->key();
return true;
} else {
return false;
}
} else {
// pass the event on to the parent class
return QMainWindow::eventFilter(obj, event);
}
}
If you want to set more specific event filter on multiple widgets you can refer following code:
class KeyPressEater : public QObject
{
Q_OBJECT
protected:
bool eventFilter(QObject *obj, QEvent *event);
};
bool KeyPressEater::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
qDebug("Ate key press %d", keyEvent->key());
return true;
} else {
// standard event processing
return QObject::eventFilter(obj, event);
}
}
KeyPressEater *keyPressEater = new KeyPressEater(this);
QPushButton *pushButton = new QPushButton(this);
pushButton->installEventFilter(keyPressEater);

QGraphicsPixmapItem mouseMoveEvent when not grabbing

I am working on a C++ application with Qt 4.8 as the GUI framework:
A subclassed QGraphicsView rendering a subclassed QGraphicsScene containing one or more subclassed QGraphicsPixMapItem(s) in which I need to know the mouse cursor's relative pixel position.
Following How to show pixel position and color from a QGraphicsPixmapItem I subclass QGraphicsPixmapItem:
class MyGraphicsPixmapItem : public QObject, public QGraphicsPixmapItem
{
Q_OBJECT
public:
explicit MyGraphicsPixmapItem(QGraphicsItem *parent = 0);
signals:
public slots:
void mouseMoveEvent(QGraphicsSceneMouseEvent * event);
void mousePressEvent(QGraphicsSceneMouseEvent *event);
};
and implement constructor and handler:
MyGraphicsPixmapItem::MyGraphicsPixmapItem(QGraphicsItem *parent) : QGraphicsPixmapItem(parent)
{
qDebug() << "constructor mygraphicspixmapitem";
setCacheMode(NoCache);
setAcceptHoverEvents(true);
setFlag(QGraphicsItem::ItemIsSelectable,true);
}
void MyGraphicsPixmapItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event)
{
QPointF mousePosition = event->pos();
qDebug() << "mouseMoveEvent";
qDebug() << mousePosition;
QGraphicsPixmapItem::mouseMoveEvent(event);
}
I have also subclassed QGraphicsView and QGraphicsScene with respective mouseMoveEvent handlers that pass the event further down successfully:
void MyGraphicsScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
qDebug() << "QGraphicsScene: mouseMoveEvent";
QGraphicsScene::mouseMoveEvent(event);
}
However, although MyGraphicsView is configured with ...
setMouseTracking(true);
setInteractive(true);
... MyGraphicsPixmapItem only executes the mouseMoveEvent handler when being clicked or after setting it as grabber:
void MyGraphicsPixmapItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
qDebug() << QString("item clicked at: %1, %2").arg( event->pos().x()).arg( event->pos().y() );
event->accept();
grabMouse();
}
I would like to know whether I am making a mistake or the solution given in the above-mentioned answer is flawed or incomplete. Further, I would like to know whether the mouseMoveEvent handler can be triggered without the QGraphicsPixmapItem being configured as 'grabber'. It is also acceptable if the configuration as grabber occurs automatically when the mouse first moves onto the item.
Here is a thread where a very similar problem seems to be related to the item's reference, but since I add the item to the scene like this:
thepixMapItem = new MyGraphicsPixmapItem();
scene->addItem(thepixMapItem);
I suppose this is not related.
The solution is to reimplement or filter the item's hoverMoveEvent, as mouseMoveEvent only triggers when receiving a mouse press:
If you do receive this event, you can be certain that this item also
received a mouse press event, and that this item is the current mouse
grabber.