QWidget keyPressEvent override - c++

I'm trying for half an eternity now overriding QWidgets keyPressEvent function in QT but it just won't work. I've to say i am new to CPP, but I know ObjC and standard C.
My problem looks like this:
class QSGameBoard : public QWidget {
Q_OBJECT
public:
QSGameBoard(QWidget *p, int w, int h, QGraphicsScene *s);
signals:
void keyCaught(QKeyEvent *e);
protected:
virtual void keyPressEvent(QKeyEvent *event);
};
QSGameBoard is my QWidget subclass and i need to override the keyPressEvent and fire a SIGNAL on each event to notify some registered objects.
My overridden keyPressEvent in QSGameBoard.cpp looks like this:
void QSGameBoard::keyPressEvent(QKeyEvent *event) {
printf("\nkey event in board: %i", event->key());
//emit keyCaught(event);
}
When i change QSGameBoard:: to QWidget:: it receives the events, but i cant emit the signal because the compiler complains about the scope. And if i write it like this the function doesn't get called at all.
What's the problem here?

EDIT:
As pointed out by other users, the method I outlined originally is not the proper way to resolve this.
Answer by Vasco Rinaldo
Use Set the FocusPolicy to Qt::ClickFocus to get the keybordfocus by
mouse klick. setFocusPolicy(Qt::ClickFocus);
The previous (albeit imperfect) solution I gave is given below:
Looks like your widget is not getting "focus". Override your mouse press event:
void QSGameBoard::mousePressEvent ( QMouseEvent * event ){
printf("\nMouse in board");
setFocus();
}
Here's the source code for a working example:
QSGameBoard.h
#ifndef _QSGAMEBOARD_H
#define _QSGAMEBOARD_H
#include <QWidget>
#include <QGraphicsScene>
class QSGameBoard : public QWidget {
Q_OBJECT
public:
QSGameBoard(QWidget *p, int w, int h, QGraphicsScene *s);
signals:
void keyCaught(QKeyEvent *e);
protected:
virtual void keyPressEvent(QKeyEvent *event);
void mousePressEvent ( QMouseEvent * event );
};
#endif /* _QSGAMEBOARD_H */
QSGameBoard.cpp
#include <QKeyEvent>
#include <QLabel>
#include <QtGui/qgridlayout.h>
#include <QGridLayout>
#include "QSGameBoard.h"
QSGameBoard::QSGameBoard(QWidget* p, int w, int h, QGraphicsScene* s) :
QWidget(p){
QLabel* o = new QLabel(tr("Test Test Test"));
QGridLayout* g = new QGridLayout(this);
g->addWidget(o);
}
void QSGameBoard::keyPressEvent(QKeyEvent* event){
printf("\nkey event in board: %i", event->key());
}
void QSGameBoard::mousePressEvent ( QMouseEvent * event ){
printf("\nMouse in board");
setFocus();
}
main.cpp
#include <QtGui/QApplication>
#include <QtGui/qmainwindow.h>
#include "QSGameBoard.h"
int main(int argc, char *argv[]) {
// initialize resources, if needed
// Q_INIT_RESOURCE(resfile);
QApplication app(argc, argv);
QMainWindow oM;
QGraphicsScene o;
QSGameBoard a(&oM, 1, 2, &o);
oM.setCentralWidget(&a);
a.show();
oM.show();
// create and show your widgets here
return app.exec();
}

You don't have to reimplement mousePressEvent yourself just to call setFocus. Qt planed it already.
Set the FocusPolicy to Qt::ClickFocus to get the keybordfocus by mouse klick.
setFocusPolicy(Qt::ClickFocus);
As said in the manual:
This property holds the way the widget accepts keyboard focus.
The policy is Qt::TabFocus if the widget accepts keyboard focus by tabbing, Qt::ClickFocus if the widget accepts focus by clicking, Qt::StrongFocus if it accepts both, and Qt::NoFocus (the default) if it does not accept focus at all.
You must enable keyboard focus for a widget if it processes keyboard events. This is normally done from the widget's constructor. For instance, the QLineEdit constructor calls setFocusPolicy(Qt::StrongFocus).
If the widget has a focus proxy, then the focus policy will be propagated to it.

Set the FocusPolicy to Qt::ClickFocus to get the keybordfocus by mouse klick.
setFocusPolicy(Qt::ClickFocus);

Related

Qt Transparent for selected Mouse Events

C++ Qt newbe here. I work with a QDial object that is intended to be controlled with a mouse wheel, it works fine as such, emitting valueChanged() signals when necessary.
I would like to put a semi-transparent QToolButton on top of it, allowing users to click on the button (and set QDial value to a pre-defined number) while maintaining the ability to use the mouse wheel to control QDial as usual.
I experimented a bit with the TransparentForMouseEvents attribute:
ui->toolButton_Example->setAttribute(Qt::WA_TransparentForMouseEvents);
The problem is - the above code switches off all events, including the ability to emit the clicked() signal.
Is there a way to make a QToolButton transparent selectively for MouseWheelEvents while preserving the ability to respond to MouseClick events? Or would this require rewriting the event filter from scratch?
EDIT: Just to clarify - This question is about making QToolButton transparent to MouseWheel EVENTS while still allowing it to respond to MouseClick EVENTS. It is not about making the button transparent in the graphical sense.
SOLUTION
OK, problem solved the traditional way by subclassing QDial and overriding MousePressEvent and MouseReleaseEvent:
#include <QDial>
#include <QMouseEvent>
class QSuperDial : public QDial {
public:
QSuperDial (QWidget *parent = nullptr) : QDial(parent) {
}
virtual void mousePressEvent (QMouseEvent *event) override {
emit sliderPressed();
}
virtual void mouseMoveEvent (QMouseEvent * event) override {
}
virtual void mouseReleaseEvent (QMouseEvent *event) override {
}
};
Promoting QDial to QSuperDial results in a QDial object that 'behaves' like a button when pressed, emitting sliderPressed signal, while still being responsive to MouseWheelEvent (like a normal QDial).
I think this is the simplest and the most 'Qt-like' solution, but please do correct me if I'm mistaken.
You can use QObject::installEventFilter to have the parent object filter the events before they reach the tool button. Then, override the parent's QObject::eventFilter to handle/ignore the event.
I create an example below:
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QToolButton>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
bool eventFilter(QObject *watched, QEvent *event) override;
private:
QToolButton tool_button_ignored_;
QToolButton tool_button_handled_;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include <QDebug>
#include <QEvent>
#include <QHBoxLayout>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
tool_button_ignored_.setObjectName("tool_button_ignored_");
tool_button_ignored_.setText("Ignored button");
tool_button_ignored_.installEventFilter(this);
tool_button_handled_.setObjectName("tool_button_handled_");
tool_button_handled_.setText("Handled button");
tool_button_handled_.installEventFilter(this);
QWidget *central_widget = new QWidget{this};
QHBoxLayout *layout = new QHBoxLayout{central_widget};
layout->addWidget(&tool_button_ignored_);
layout->addWidget(&tool_button_handled_);
this->setCentralWidget(central_widget);
}
MainWindow::~MainWindow()
{
}
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
if (watched != &tool_button_ignored_ || event->type() != QEvent::Wheel)
{
qDebug() << event->type() << watched->objectName() << "handled";
return QMainWindow::eventFilter(watched, event);
}
else
{
qDebug() << event->type() << watched->objectName() << "ignored";
return true; // stop being handled further
}
}

Drag item from QTreeWidget to QGraphicsView

I've the following situation:
Basically I've a QTreeWidget with some items, and a canvas that's a subclass of a QGraphicsView. What I want to accomplish is to drag a QTreeWidgetItem in the QGraphicsView subclass. When the mouse is released in the QGraphicsView subclass I want to create a new shape (let's say a circle) with some data of the dragged item (let's say the name itself written inside the circle).
I was able to enable the drag from the QTreeWidget by using the setDragEnabled(true) method, and I'm able to receive the event in the QGraphicsView, because when I enter its area it calls the dragEnterEvent.
In my subclass I've a QGraphicsScene, like this:
#ifndef SEQUENCECANVAS_HPP_
#define SEQUENCECANVAS_HPP_
#include <QWidget>
#include <QGraphicsScene>
#include <QGraphicsView>
class SequenceCanvas : public QGraphicsView {
Q_OBJECT
public:
SequenceCanvas(QWidget* parent = nullptr);
virtual ~SequenceCanvas() = default;
protected:
void dragEnterEvent(QDragEnterEvent* event) override;
void dropEvent(QDropEvent* event) override;
private:
void createWidgets();
void createLayout();
private:
QGraphicsScene m_scene;
};
#endif // !SEQUENCECANVAS_HPP_
#include "SequenceCanvas.hpp"
#include <QString>
#include <QHBoxLayout>
#include <QDragEnterEvent>
#include <QMimeData>
SequenceCanvas::SequenceCanvas(QWidget* parent) :
QGraphicsView(parent) {
createWidgets();
createLayout();
setScene(&m_scene);
setAcceptDrops(true);
}
void SequenceCanvas::dragEnterEvent(QDragEnterEvent* event) {
event->acceptProposedAction(); // no filter at the moment I just want to test
}
void SequenceCanvas::dropEvent(QDropEvent* event) {
int i = 0; // just for putting a breakpoint now. Its breakpoint is never raised
}
void SequenceCanvas::createWidgets() {
}
void SequenceCanvas::createLayout() {
}
Even if the dragEnterEvent is called when my mouse enter my widget during the drag, the dropEvent method is not called, so when I release the mouse inside my SequenceCanvas class nothing happens.
Basically I've two questions:
How can I raise the drop event inside my SequenceCanvas class that's a subclass of QGraphicsView?
How can I pass custom data (let's say a vector of strings) with the drop event, so I can pass all needed information for managing the event?
EDIT:
I missed to reimplement the void dragMoveEvent(QDragMoveEvent* event) method. I've added it and now I receive drop events. I need to know how to pass custom data with a drag-drop event now... Thanks to zeFrenchy.
My class body now is:
SequenceCanvas::SequenceCanvas(QWidget* parent) :
QGraphicsView(parent) {
createWidgets();
createLayout();
setScene(&m_scene);
setAcceptDrops(true);
bool ok = acceptDrops();
}
///////////////////////////////////////////////////////////////////////////////
// VIRTUAL PROTECTED SECTION //
///////////////////////////////////////////////////////////////////////////////
void SequenceCanvas::dragEnterEvent(QDragEnterEvent* event) {
event->acceptProposedAction();
}
void SequenceCanvas::dragMoveEvent(QDragMoveEvent* event) {
event->acceptProposedAction();
}
void SequenceCanvas::dropEvent(QDropEvent* event) {
int i = 0;
}
///////////////////////////////////////////////////////////////////////////////
// PRIVATE SECTION //
///////////////////////////////////////////////////////////////////////////////
void SequenceCanvas::createWidgets() {
}
void SequenceCanvas::createLayout() {
}
The documentation says the following about DragMoveEvent:
A widget will receive drag move events repeatedly while the drag is within its boundaries, if it accepts drop events and enter events. The widget should examine the event to see what kind of data it provides, and call the accept() function to accept the drop if appropriate.
So you should be provide an override for dragMoveEvent(QDragMoveEvent* event) in which you simply accept the proposed action.

How to know when down-arrow of Combo box is clicked?

I have a ComboBox and set it to be edited.
QComboBox *myCombo = new QComboBox(this);
myCombo->setEditable(true);
myCombo->setStyleSheet("QComboBox::down-arrow{image: url(:/bulb.png);}");
myCombo->setCursor( QCursor( Qt::PointingHandCursor ) );
So now when i click onto the editing field, nothing happen. But what I need is, when I click onto the bulb (which is the down-arrow), something (like a table or a dialog....) should be appeared. How can I recognize this click event in this case? I looked at the list of signals for combo box but could not find any signal for that.
By overwriting the mousePressEvent() method you must use hitTestComplexControl() method to know that QStyle::SubControl has been pressed by issuing a signal if it is QStyle::SC_ComboBoxArrow.
#include <QtWidgets>
class ComboBox: public QComboBox
{
Q_OBJECT
public:
using QComboBox::QComboBox;
signals:
void clicked();
protected:
void mousePressEvent(QMouseEvent *event) override{
QComboBox::mousePressEvent(event);
QStyleOptionComboBox opt;
initStyleOption(&opt);
QStyle::SubControl sc = style()->hitTestComplexControl(QStyle::CC_ComboBox, &opt, event->pos(), this);
if(sc == QStyle::SC_ComboBoxArrow)
emit clicked();
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ComboBox w;
w.setEditable(true);
w.setStyleSheet("QComboBox::down-arrow{image: url(:/bulb.png);}");
QObject::connect(&w, &ComboBox::clicked, [](){
qDebug()<<"clicked";
});
w.show();
return a.exec();
}
#include "main.moc"
Although showPopup() is a possible option this can be called directly without the down-arrow being pressed, for example by calling it directly: myCombo->showPopup() so it is not the correct option.
A possible solution is to subclass QComboBox and reimplement showPopup() virtual method:
.h:
#ifndef COMBOBOXDROPDOWN_H
#define COMBOBOXDROPDOWN_H
#include <QComboBox>
#include <QDebug>
class ComboBoxDropDown : public QComboBox
{
public:
ComboBoxDropDown(QWidget *parent = nullptr);
void showPopup() override;
};
#endif // COMBOBOXDROPDOWN_H
.cpp:
#include "comboboxdropdown.h"
ComboBoxDropDown::ComboBoxDropDown(QWidget *parent)
: QComboBox (parent)
{
}
void ComboBoxDropDown::showPopup()
{
//QComboBox::showPopup();
qDebug() << "Do something";
}

"QPainter::drawRects: Painter not active " error C++/QT

I'm a beginner at Qt
and c++ and I wanted to see how to use a QPainter and events in Qt but I got stuck because of an error message during the execution, my original code:
the main.cpp
#include "customwidget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QScopedPointer<QWidget> widget(new customWidget());
widget->resize(240, 120);
widget->show();
return a.exec();
}
and the header:
#ifndef CUSTOMWIDGET_H
#define CUSTOMWIDGET_H
#include <QWidget>
#include <QMouseEvent>
#include <QPoint>
#include <QPainter>
class customWidget : public QWidget
{
Q_OBJECT
public:
explicit customWidget(QWidget *parent = 0);
void paintEvent(QPaintEvent *);
void mouseMoveEvent(QMouseEvent *event);
void mousePressEvent(QMouseEvent *event);
private:
QPoint m_mousePos;
QRect m_r2;
signals:
void needToRepaint();
public slots:
};
#endif // CUSTOMWIDGET_H
and the .cpp:
#include "customwidget.h"
customWidget::customWidget(QWidget *parent) : QWidget(parent)
{
QRect m_r2;
QPoint m_mousePos;
QObject::connect(this, SIGNAL(needToRepaint()), this, SLOT(repaint()));
}
void customWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
// ############ First Rectangle ****************************************
QRect r1 = rect().adjusted(10, 10, -10, -10);
painter.setPen(QColor("#FFFFFF"));
painter.drawRect(r1);
// ############ Seconde Rectangle ****************************************
QRect r2(QPoint(0, 0), QSize(100, 100));
m_r2.moveCenter(m_mousePos);
QPainter painter2;
QPen pen;
painter2.setPen(QColor("#000000"));
pen.setWidth(3);
painter2.setPen(pen);
painter2.drawRect(m_r2);
update();
}
void customWidget::mouseMoveEvent(QMouseEvent *event)
{
m_mousePos = event->pos();
emit needToRepaint();
}
I tried to search it on the web and saw that it's because the QPainter isn't located in the paintEvent but it's not the case in my code, thanks for your help.
You only need one painter. The second one wasn't activated, and you don't need it anyway.
Don't ever call repaint() unless you somehow absolutely need the painting to be done before repaint() returns (that's what happens!). If you keep the event loop running properly, you won't ever need that.
Don't call update() from paintEvent(): it's nonsense (literally).
When you wish to repaint the widget, call update(): it schedules an update from the event loop. Multiple outstanding updates are coalesced to keep the event loop functional and prevent event storms.
Let the compiler generate even more memory management code for you. You've done the first step by using smart pointers - that's good. Now do the second one: hold the instance of CustomWidget by value. It doesn't have to be explicitly dynamically allocated. C++ is not C, you can leverage values.
In a simple test case, you don't want three files. Your code should fit in as few lines as possible, in a single main.cpp. If you need to moc the file due to Q_OBJECT macros, add #include "main.moc" at the end, and re-run qmake on the project to take notice of it.
This is how such a test case should look, after fixing the problems. Remember: it's a test case, not a 100kLOC project. You don't need nor want the meager 35 lines of code spread across three files. Moreover, by spreading out the code you're making it harder for yourself to comprehend.
Even in big projects, unless you can show significant build time improvements if doing the contrary, you can have plenty of small classes implemented Java-style completely in the header files. That's about the only Java-style-anything that belongs in C++.
// https://github.com/KubaO/stackoverflown/tree/master/questions/simple-paint-38796140
#include <QtWidgets>
class CustomWidget : public QWidget
{
QPoint m_mousePos;
public:
explicit CustomWidget(QWidget *parent = nullptr) : QWidget{parent} {}
void paintEvent(QPaintEvent *) override;
void mouseMoveEvent(QMouseEvent *event) override {
m_mousePos = event->pos();
update();
}
};
void CustomWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
auto r1 = rect().adjusted(10, 10, -10, -10);
painter.setPen(Qt::white);
painter.drawRect(r1);
auto r2 = QRect{QPoint(0, 0), QSize(100, 100)};
r2.moveCenter(m_mousePos);
painter.setPen(QPen{Qt::black, 3, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin});
painter.drawRect(r2);
}
int main(int argc, char ** argv) {
QApplication app{argc, argv};
CustomWidget w;
w.show();
return app.exec();
}
This error can happen too when the QPixmap used to create the QPainter(QPixmap) is invalid (if there is no file at such path).
Be sure your QPixmap is correct before painting on it.

Qt paint figures at one window

I create class Widget, it creates window, this class paints something on the window (i.e. it works as I want).
I create yet one class, Circle, I want to paint on the window of class Widget.
I pass adress of Widget and try to paint on Widget using QPainter paint (address of Widget); (in the instance of Circle) but i don't see anything.
I've tried to make code as shorter as possible during the execution of program I type out address of object Widget. It doesn't change. It means that the address of Widget was passed right.
Everywhere, where I type out address of Widget I receive the same address. Here is the code:
header Widget
class Widget : public QWidget
{
public:
int mi,mcount;
Widget(QWidget *parent = 0);
QPaintEvent *ev;
virtual void paintEvent(QPaintEvent *);
void drawcircle();
};
Widget.cpp
Widget::Widget(QWidget *parent) : QWidget(parent)
{
QWidget::paintEvent(ev);
qDebug()<<this<<"\n"; //
}
void Widget::drawcircle()
{
QPainter paint(this);
paint.drawEllipse(0,0,100,100);
}
void Widget::paintEvent(QPaintEvent *ev)
{ this->drawcircle(); }
header Circle.h
class Circle :public QWidget
{
public:
Circle(Widget *widget); // i do trick here!!!
Widget *mwidg;
QPaintEvent *ev;
virtual void paintEvent(QPaintEvent *);
void drawcircle(Widget *mwidg);
};
Circle.cpp
Circle::Circle(Widget *widget)
{
qDebug()<<"circle widget"<<widget;
QWidget::paintEvent(ev);
mwidg=widget;
qDebug()<<"\n"<<mwidg;
}
void Circle::paintEvent(QPaintEvent *ev)
{ qDebug()<<"circle paintEvent mwidget"<<mwidg<<"\n";
this->drawcircle(mwidg);
}
void Circle::drawcircle(Widget *mwidg)
{
QPainter paint(mwidg);
paint.drawEllipse(20,10,40,40);
paint.drawLine(0,0,500,500);
}
main
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget *w=new Widget;
qDebug()<<"main address of widget"<<w<<"\n";
Circle *f=new Circle(w);
w->show();
return a.exec();
}
program is compiled and linked successful
What exactly are you trying to achieve? You can only paint on any widget in it's own paintEvent() handler, and you should not call paintEvent() yourself, it won't work. Also, get rid of the QPaintEvent member variables.
I would suggest that you make Circle a child of Widget, and then paint the circle from Circle::paintEvent(). Alternatively, use QGraphicsView.
well , thank you for your attempts to help
but all that i was needing:
this -> setParent(widget);
in costructor Circle::Circle, if somebody'll want to see my solve,one can see that figures are moved
source code is here source code