10

In Qt, how do I take a screenshot of a specific window (i.e. suppose I had Notepad up and I wanted to take a screenshot of the window titled "Untitled - Notepad")? In their screenshot example code, they show how to take a screenshot of the entire desktop:

originalPixmap = QPixmap::grabWindow(QApplication::desktop()->winId());

How would I get the winId() for a specific window (assuming I knew the window's title) in Qt?

Thanks

Switch
  • 5,126
  • 12
  • 34
  • 40

5 Answers5

6

I'm pretty sure that's platform-specific. winIds are HWNDs on Windows, so you could call FindWindow(NULL, "Untitled - Notepad") in the example you gave.

ChrisV
  • 3,363
  • 16
  • 19
2

Look at QDesktopWidget class. It's inherited from QWidget so there is literally no problem of taking screenshot:

QPixmap pm(QDesktopWidget::screenGeometry().size());
QDesktopWidget::screen().render(&pm); // pm now contains screenshot
GreenScape
  • 7,191
  • 2
  • 34
  • 64
  • 1
    For version `4.8` I had to make little changes to your snippet. Mainly: create an object of type `QDesktopWidget` to call `screenGeometry()` and `screen()`, and change `screen().render()` to `screen()->render()`, as `screen()` returns a `QWidget*`. – Adri C.S. Apr 22 '15 at 10:38
1

Also look at WindowFromPoint and EnumChildWindows. The latter could allow you to prompt the user to disambiguate if you had multiple windows with the same title.

Jake Petroules
  • 23,472
  • 35
  • 144
  • 225
1

Have a look at Screenshot example

In short:

QScreen *screen = QGuiApplication::primaryScreen();
if (screen)
    QPixmap originalPixmap = screen->grabWindow(0);
Nya
  • 310
  • 2
  • 10
  • This answer is not about "Taking screenshot of a specific window". This is about taking screenshot of whole screen. – Alok Aug 18 '21 at 11:07
-1

Although this has already been answered, just for the sake of completeness, I'll add to Trevor Boyd Smith's post (see above) a code-snippet example:

void MainWindow::on_myButton_GUI_Screeshot_clicked()
{
    QPixmap qPixMap = QPixmap::grabWidget(this);  // *this* is window pointer, the snippet     is in the mainwindow.cpp file

    QImage qImage = qPixMap.toImage();

    cv::Mat GUI_SCREENSHOT = cv::Mat(         qImage.height(),
                                              qImage.width(), CV_8UC4,
                                      (uchar*)qImage.bits(),
                                              qImage.bytesPerLine()  );

    cv::imshow("GUI_SCREENSHOT",GUI_SCREENSHOT);
}
dim_tz
  • 1,451
  • 5
  • 20
  • 37