Avoid crashing in the quickwidgets example after closing the subwindow

Closing the window deletes m_quickWidget; so we disable the menu items
for grabbing from it, because those cannot work. Also add asserts.

Fixes: QTBUG-120296
Pick-to: 6.5 6.2 5.15
Change-Id: I68154c2d1e4553c771815e29cbe3b095d85893f1
Reviewed-by: Axel Spoerl <axel.spoerl@qt.io>
(cherry picked from commit f719ee6408)
Reviewed-by: Qt Cherry-pick Bot <cherrypick_bot@qt-project.org>
(cherry picked from commit a49d309b4a)
This commit is contained in:
Shawn Rutledge 2023-12-28 19:15:14 -07:00 committed by Qt Cherry-pick Bot
parent 1570bd5f8e
commit 08c01f6259
1 changed files with 15 additions and 3 deletions

View File

@ -63,14 +63,22 @@ MainWindow::MainWindow()
setCentralWidget(centralWidget);
QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(tr("Grab framebuffer"), this, &MainWindow::grabFramebuffer);
fileMenu->addAction(tr("Render to pixmap"), this, &MainWindow::renderToPixmap);
fileMenu->addAction(tr("Grab via grabToImage"), this, &MainWindow::grabToImage);
auto grabAction = fileMenu->addAction(tr("Grab framebuffer"), this, &MainWindow::grabFramebuffer);
auto renderAction = fileMenu->addAction(tr("Render to pixmap"), this, &MainWindow::renderToPixmap);
auto grabToImageAction = fileMenu->addAction(tr("Grab via grabToImage"), this, &MainWindow::grabToImage);
fileMenu->addAction(tr("Quit"), qApp, &QCoreApplication::quit);
QMenu *windowMenu = menuBar()->addMenu(tr("&Window"));
windowMenu->addAction(tr("Add tab widget"), this,
[this, centralWidget] { createQuickWidgetsInTabs(centralWidget); });
connect(m_quickWidget, &QObject::destroyed, this,
[this, grabAction, renderAction, grabToImageAction] {
m_quickWidget = nullptr;
grabAction->setEnabled(false);
renderAction->setEnabled(false);
grabToImageAction->setEnabled(false);
});
}
void MainWindow::createQuickWidgetsInTabs(QMdiArea *mdiArea)
@ -123,6 +131,7 @@ void MainWindow::quickWidgetStatusChanged(QQuickWidget::Status status)
{
if (status == QQuickWidget::Error) {
QStringList errors;
Q_ASSERT(m_quickWidget);
const auto widgetErrors = m_quickWidget->errors();
for (const QQmlError &error : widgetErrors)
errors.append(error.toString());
@ -147,12 +156,14 @@ template<class T> void saveToFile(QWidget *parent, T *saveable)
void MainWindow::grabFramebuffer()
{
Q_ASSERT(m_quickWidget);
QImage image = m_quickWidget->grabFramebuffer();
saveToFile(this, &image);
}
void MainWindow::renderToPixmap()
{
Q_ASSERT(m_quickWidget);
QPixmap pixmap(m_quickWidget->size());
m_quickWidget->render(&pixmap);
saveToFile(this, &pixmap);
@ -165,6 +176,7 @@ void MainWindow::grabToImage()
fd.setDefaultSuffix("png");
fd.selectFile("test_grabToImage.png");
if (fd.exec() == QDialog::Accepted) {
Q_ASSERT(m_quickWidget);
QMetaObject::invokeMethod(m_quickWidget->rootObject(), "performLayerBasedGrab",
Q_ARG(QVariant, fd.selectedFiles().first()));
}