diff --git a/src/plugins/platforms/xcb/qxcbconnection.cpp b/src/plugins/platforms/xcb/qxcbconnection.cpp
index db2179c73f581b9d70ac3cafdda2b3987cbbc3c7..209c7bb187b6c481f450d14e9fb438969fc7ee8e 100644
--- a/src/plugins/platforms/xcb/qxcbconnection.cpp
+++ b/src/plugins/platforms/xcb/qxcbconnection.cpp
@@ -1720,4 +1720,24 @@ bool QXcbConnection::xi2PrepareXIGenericDeviceEvent(xcb_ge_event_t *event, int o
 }
 #endif // defined(XCB_USE_XINPUT2) || defined(XCB_USE_XINPUT2_MAEMO)
 
+QXcbConnectionGrabber::QXcbConnectionGrabber(QXcbConnection *connection)
+    :m_connection(connection)
+{
+    connection->grabServer();
+}
+
+QXcbConnectionGrabber::~QXcbConnectionGrabber()
+{
+    if (m_connection)
+        m_connection->ungrabServer();
+}
+
+void QXcbConnectionGrabber::release()
+{
+    if (m_connection) {
+        m_connection->ungrabServer();
+        m_connection = 0;
+    }
+}
+
 QT_END_NAMESPACE
diff --git a/src/plugins/platforms/xcb/qxcbconnection.h b/src/plugins/platforms/xcb/qxcbconnection.h
index cba26e148cc1365be0e5a0d43de47a7cd6d380ee..883ee95e227b14ce7ac87d247a3f9dccc81f00ac 100644
--- a/src/plugins/platforms/xcb/qxcbconnection.h
+++ b/src/plugins/platforms/xcb/qxcbconnection.h
@@ -585,6 +585,15 @@ xcb_generic_event_t *QXcbConnection::checkEvent(T &checker)
     return 0;
 }
 
+class QXcbConnectionGrabber
+{
+public:
+    QXcbConnectionGrabber(QXcbConnection *connection);
+    ~QXcbConnectionGrabber();
+    void release();
+private:
+    QXcbConnection *m_connection;
+};
 
 #ifdef Q_XCB_DEBUG
 template <typename cookie_t>
diff --git a/src/plugins/platforms/xcb/qxcbdrag.cpp b/src/plugins/platforms/xcb/qxcbdrag.cpp
index 8ce4ef5f047fd930b649abeb0a1d877c27873a7a..db736cef4e7388269ac6cfd239de51e55b4ec983 100644
--- a/src/plugins/platforms/xcb/qxcbdrag.cpp
+++ b/src/plugins/platforms/xcb/qxcbdrag.cpp
@@ -1141,7 +1141,7 @@ bool QXcbDrag::dndEnable(QXcbWindow *w, bool on)
             if (desktop_proxy) // *WE* already have one.
                 return false;
 
-            connection()->grabServer();
+            QXcbConnectionGrabber grabber(connection());
 
             // As per Xdnd4, use XdndProxy
             xcb_window_t proxy_id = xdndProxy(connection(), w->xcb_window());
@@ -1157,7 +1157,6 @@ bool QXcbDrag::dndEnable(QXcbWindow *w, bool on)
                                     XCB_ATOM_WINDOW, 32, 1, &proxy_id);
             }
 
-            connection()->ungrabServer();
         } else {
             xdnd_widget = w;
         }