diff --git a/src/opengl/qgl_p.h b/src/opengl/qgl_p.h
index 9a58beb3d7dac7cd3b06043697a04627ef1f0641..ff9baf897165d8d830777795455a7be9eeb2c420 100644
--- a/src/opengl/qgl_p.h
+++ b/src/opengl/qgl_p.h
@@ -132,6 +132,7 @@ class Q_OPENGL_EXPORT QGLWidgetPrivate : public QWidgetPrivate
 public:
     QGLWidgetPrivate() : QWidgetPrivate()
                        , disable_clear_on_painter_begin(false)
+                       , parent_changing(false)
     {
     }
 
@@ -142,7 +143,7 @@ public:
     bool renderCxPm(QPixmap *pixmap);
     void cleanupColormaps();
     void aboutToDestroy() {
-        if (glcx)
+        if (glcx && !parent_changing)
             glcx->reset();
     }
 
@@ -153,6 +154,7 @@ public:
     QGLColormap cmap;
 
     bool disable_clear_on_painter_begin;
+    bool parent_changing;
 };
 
 // QGLContextPrivate has the responsibility of creating context groups.
diff --git a/src/opengl/qgl_qpa.cpp b/src/opengl/qgl_qpa.cpp
index f3388ee5efc63950c33379f84c244914dc451bf3..6e698bf939900de3babb0fad6b821d32adb611d4 100644
--- a/src/opengl/qgl_qpa.cpp
+++ b/src/opengl/qgl_qpa.cpp
@@ -362,6 +362,15 @@ void QGLWidgetPrivate::cleanupColormaps()
 
 bool QGLWidget::event(QEvent *e)
 {
+    Q_D(QGLWidget);
+
+    // A re-parent will destroy the window and re-create it. We should not reset the context while it happens.
+    if (e->type() == QEvent::ParentAboutToChange)
+        d->parent_changing = true;
+
+    if (e->type() == QEvent::ParentChange)
+        d->parent_changing = false;
+
     return QWidget::event(e);
 }
 
diff --git a/src/widgets/kernel/qwidget_qpa.cpp b/src/widgets/kernel/qwidget_qpa.cpp
index 590ebed5ebfc18065d731bce6397a05f967abba7..3b6c9ca4487d45fbe7018f30bc3fa00457800c2e 100644
--- a/src/widgets/kernel/qwidget_qpa.cpp
+++ b/src/widgets/kernel/qwidget_qpa.cpp
@@ -263,10 +263,8 @@ void QWidgetPrivate::setParent_sys(QWidget *newparent, Qt::WindowFlags f)
     bool explicitlyHidden = q->testAttribute(Qt::WA_WState_Hidden) && q->testAttribute(Qt::WA_WState_ExplicitShowHide);
 
     // Reparenting toplevel to child
-    if (!(f&Qt::Window) && (oldFlags&Qt::Window) && !q->testAttribute(Qt::WA_NativeWindow)) {
-        //qDebug() << "setParent_sys() change from toplevel";
+    if (wasCreated && !(f & Qt::Window) && (oldFlags & Qt::Window) && !q->testAttribute(Qt::WA_NativeWindow))
         q->destroy();
-    }
 
     adjustFlags(f, q);
     data.window_flags = f;