QMouseEvent::pos() returns different values on different OSes

150 views Asked by At

I have created a simple example which is just a window with a red rectangle. This rectangle has 50px margins from top, bottom, right and left. The value of 50px is definitely hardcoded and cannot be changed from the application.

The (0,0) point of the widget is located in the left-top corner. That means, that when I click on the left-top corner of the red rectangle (a little bit pixel hunting, but that's OK), I anticipate to click to the position with the coordinates of (50,50).

But, for a reason that I cannot understand:

  • It is true on Windows only.
  • On Linux I get (51, 51), a single pixel shift.
  • On MacOS I get (52, 52), a two pixels shift.

Is that a known behavior? Or how could I fix it?

main.cpp

#include "mainwindow.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

mainwindow.cpp

#include "mainwindow.h"

#include <QDebug>

#include <QPainter>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    setFixedSize(800, 600);
}

void MainWindow::mousePressEvent(QMouseEvent* me) {
    auto pos = me->pos();
    qDebug() << "pos: " << pos.x() << "," << pos.y();
}

void MainWindow::paintEvent(QPaintEvent *) {
    QPainter p(this);
    p.fillRect(50, 50, width() - 100, height() - 100, Qt::red);
    p.setPen(Qt::black);
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QMouseEvent>

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);

    void mousePressEvent(QMouseEvent* me) override;
    void paintEvent(QPaintEvent *pe) override;
};
#endif // MAINWINDOW_H

incorrect_pos_on_different_os.pro

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++17

CONFIG += console

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    main.cpp \
    mainwindow.cpp

HEADERS += \
    mainwindow.h

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

This problem is reproducible on Qt 5.15.2 (that's pretty old, I know, but I cannot upgrade it right now, I need to use what I have).

I use:

  • I use Qt 5.15.*
  • Windows 10
  • Ubuntu 20.04
  • MacOS Monterey
0

There are 0 answers