1

I am Using Qt 4.8 I am trying to bind mouse cursor to the center of my application.

If application is in fullscreen it works with following code

int  middleX = QApplication::desktop()->width() >> 1;
int  middleY = QApplication::desktop()->height() >> 1;

QPoint newMousePos;
newMousePos.setX(middleX);
newMousePos.setY(middleY);
QCursor::setPos(newMousePos);

and it works.

But how do I do this when application is not fullscreen mode? I tried few codes from the web but I could not found them working. I understand that I need to get current geometry of window i.e. current window position w.r.t. monitor and width and height of window.

but what are the functions to be used for that?

Thanks in advance

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Adorn
  • 1,403
  • 1
  • 23
  • 46
  • Shouldn't you rename the question to "how to put the cursor in the middle of my application" or something like that? Because currently there is a mismatch between the title and body of the question... – dtech Mar 19 '13 at 12:01

1 Answers1

2

All it takes is this:

QCursor::setPos(geometry().center());

This will put the cursor in the dead center of your application window main widget, agnostic of the size and position of the window on the screen.

dtech
  • 47,916
  • 17
  • 112
  • 190
  • which header file do i need to include? I get error: left of '.center' must have class/struct/union – Adorn Mar 19 '13 at 12:05
  • The code sample is implying that this is being called from within a QWidget object. – vipw Mar 19 '13 at 12:06
  • @Adorn - the `geometry()` method is introduced by QWidget and is available to every QWidget derived class - QDialog, QMainWindow and pretty much every widget from the QtWidgets module. E.g. call `geometry()` on whatever the root visual representation of your application is. – dtech Mar 19 '13 at 12:07
  • I am so sorry for being this much dumb.. this error "left of '.center'.." can't seem to go away. What do I do? – Adorn Mar 19 '13 at 12:14
  • @Adorn - what do you have in you application besides a QApplication? What class is used for drawing your window? – dtech Mar 19 '13 at 12:15
  • actually the class in which I am doing this is different and doesn't actually need even QApplication, I am doing OpenGL program, so my current rendering context is OpenGL context i.e. QGLWidget. though even after adding QWidget I am still facing this error – Adorn Mar 19 '13 at 12:19
  • Well, QGLWidget inherits QWidget and has a `geometry()` method, if you aren't calling it from inside the `QGLWidget` just use `myGlWidgetInstanceName.geometry().center()` instead. Post your code if you still have problems figuring it out... – dtech Mar 19 '13 at 12:22