Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QT 5.5 Program crashes when using QApplication::activeWindow->winId() in other window

Tags:

c++

qt

I'm trying to realize the function that takes a screenshot when the global hot key was activated. And I applied this into my project so I can easily create a global hot key.

To use the screen->grabWindow(), I have to get the WinID of the active window. So I found the QApplication::activeWindow()->winId() and then used it.

QScreen *screen = QGuiApplication::primaryScreen();
QPixmap screenShot = screen->grabWindow(QApplication::activeWindow()->winId(), 0, 0, -1,-1);

However, things are going to the wrong way. When I press the hot key in other windows, the program just crashes with "untitled2.exe has stopped working".(sorry for not being able to put on an image[http://ww2.sinaimg.cn/large/bcbe8e8cgw1euarn4mcb6j20vt09ojtk.jpg ])

And I found that the same situation happens even when I simply qDebug() it. Not only winId(), but also windowTitle(), setWindowTitle() and so on.

qDebug() << QApplication::activeWindow()->winId();

Can anyone help me work it out? Thanks a lot!

like image 695
IncredibLink Avatar asked Oct 18 '25 19:10

IncredibLink


1 Answers

It crashes because QApplication::activeWindow() returns null. It will do so if no application window has the focus (this is verbatim from the documentation). No application window having focus means that none of your application windows have focus.

So, this approach simply won't work for what you're attempting to do. You need to use platform-specific ways of doing it.

like image 111
Kuba hasn't forgotten Monica Avatar answered Oct 21 '25 09:10

Kuba hasn't forgotten Monica