【问题标题】:How to capture the current screen image using Qt?如何使用 Qt 捕获当前屏幕图像?
【发布时间】:2018-04-04 15:44:07
【问题描述】:

我的自定义 QDialog 中有一个按钮,单击按钮 1 时我会发出一个信号

void MyCustomDialog::on_pushButton_1()
{
    this->hide(); //i need to hide this window before 'OnButton_1_Clicked' stuffs starts
    emit button_1_clicked();
}

在我的主窗口中,我连接了插槽并创建了实例,如下所示

void MainWindow::MainWindow()
{

    MyCustomDialog *dlg = MyCustomDialog::getInstance(this); //only single instance created
    connect(dlg, &MyCustomDialog::button_1_clicked, this, &MainWindow::OnButton_1_Clicked);
}

我正在主窗口中的一个函数中显示我的自定义对话框,如下所示

void MainWindow::dispayCustomDialog()
{
    MyCustomDialog *dlg = MyCustomDialog::getInstance();
    dlg->show();
}

下面显示了我的“OnButton_1_Clicked”插槽。我在其中使用下面的行捕获屏幕截图

void MainWindow::OnButton_1_Clicked()
{
     //capture the screen shot
     QScreen *screen = QGuiApplication::primaryScreen();
     QPixmap *map = new QPixmap(screen->grabWindow(0));
     bool result = map->save("D:/test.jpg", "JPG");
}

使用上述功能捕获屏幕后,我仍然可以在 test.jpg 文件中看到我的“MyCustomDialog”。 Qt 文档说QGuiApplication::primaryScreen 捕获应用程序的初始状态。所以我认为,这在我的情况下是可以预料的。我们还有其他解决方案来抓取当前状态的屏幕吗?

我想要实现的是在隐藏我的“MyCustomDialog”后在 OnButton_1_Clicked() 函数中抓取屏幕。

【问题讨论】:

  • 你怎么知道它是在关闭之前执行的?我刚刚试了一下,它工作正常。为此,请验证它是否被隐藏:void MainWindow::OnButton_1_Clicked() { qDebug()<< MyCustomDialog::getInstance()->isVisible(); qDebug()<<"clicked"; },我得到:false clicked。使用 Qt::QueuedConnection 的连接是不必要的,如果连接在 2 个不同线程中的 2 个对象之间,则必须激活该标志。
  • 哦。我的错。你说的对。我应该已经通过可见功能进行了验证。不幸的是,我通过在“OnButton_1_Clicked()”中抓取屏幕进行了验证。所以错误在于我的抓取屏幕功能。 QScreen *screen = QGuiApplication::primaryScreen(); QPixmap *map = new QPixmap(screen->grabWindow(0)); bool result = map->save("D:/screen.jpg", "JPG");.
  • 据我了解,QGuiApplication::primaryScreen(); 捕获了我的自定义对话框最初可见的屏幕的初始状态。
  • 所以,我应该找到另一种方法来捕获当前屏幕而不是QGuiApplication::primaryScreen()的初始屏幕。
  • 你有一个XY problem,你的问题应该集中在你的主要目标上,而不是解决一个不一定有效的可能解决方案。

标签: qt


【解决方案1】:

我找到了解决方案。在捕获屏幕之前使用延迟为 500 毫秒的单槽计时器,如下所示。这将等待我的自定义对话框正确隐藏。

void MainWindow::OnButton_1_Clicked()
{
     QTimer::singleShot(500, this, &MainWindow::shootscreen);
}

void MainWindow::shootscreen()
{
     //capture the screen shot
     QScreen *screen = QGuiApplication::primaryScreen();
     QPixmap map = screen->grabWindow(0);
     bool result = map.save("D:/test.jpg", "JPG");
}

【讨论】:

  • 不要使用指针,你正在创建你没有消除的动态内存,这是不好的做法。将其更改为:QPixmap map =screen->grabWindow(0); bool result = map.save("D:/test.jpg", "JPG");
猜你喜欢
  • 2010-10-17
  • 1970-01-01
  • 1970-01-01
  • 2012-01-20
  • 2022-01-13
  • 1970-01-01
  • 2011-04-27
  • 1970-01-01
  • 2013-06-16
相关资源
最近更新 更多