title: How to limit a Qt window in a screen?
body: <p>On Widnows or Mac, I can drag a Qt window from one screen to another. Is there an elegant way to limit the Qt window in one screen?</p>
  
  <hr>
  
  <p>Update:</p>
  
  <p>I don't want the window do a long distance jump back to the screen. So the perfect solution for me is intercepting the movement before it happens. But I could not find a way to do it. </p>
  
  <p>I did a little change to moveEvent(), setting mouse position instead of setting widget's position. Now it doesn't flicker that badly. </p>
  
  <pre><code>    auto screenNumber = QApplication::desktop()-&gt;screenNumber(this-&gt;currentHead());
      if (screenNumber &gt;= 0)
      {
          QScreen * screen = QApplication::screens().at(screenNumber);
          auto screenRect = screen-&gt;geometry();
          auto mousePosition = QCursor::pos();
  
          if (!screenRect.contains(mousePosition))
          {
              mousePosition.setX(std::max(screenRect.left(),
                  std::min(mousePosition.x(), screenRect.right())));
              mousePosition.setY(std::max(screenRect.top(),
                  std::min(mousePosition.y(), screenRect.bottom())));
              QCursor::setPos(mousePosition);
          }
      }
  </code></pre>
  
  <hr>
  
  <p>Original Post:</p>
  
  <ol>
  <li><p>I've tried to implement my own moveEvent() but the result was very ugly. The window flickered badly. And I think calling resize() in moveEvent() is not good practice. </p></li>
  <li><p>Since I dragged the title bar, there was no mouse move events passing to the window. </p></li>
  </ol>
  
  <p>code</p>
  
  <pre><code>void Cmr42DockWidget::moveEvent(QMoveEvent * event)
  {
      if (isVisible() &amp;&amp; isFloating())
      {
          auto screenNumber = QApplication::desktop()-&gt;screenNumber(this-&gt;currentHead());
          if (screenNumber &gt;= 0)
          {
              QScreen * screen = QApplication::screens().at(screenNumber);
              auto rect = geometry();
              auto screenRect = screen-&gt;geometry();
              if (!screenRect.contains(rect))
              {
                  if (rect.left() &lt; screenRect.left())
                  {
                      rect.moveLeft(screenRect.left() - 1);
                  }
                  if (rect.right() &gt; screenRect.right())
                  {
                      rect.moveRight(screenRect.right() - 1);
                  }
                  if (rect.top() &lt; screenRect.top())
                  {
                      rect.moveTop(screenRect.top() + 1);
                  }
                  if (rect.bottom() &gt; screenRect.bottom())
                  {
                      rect.moveBottom(screenRect.bottom() + 1);
                  }
                  setGeometry(rect);
              }
          }
      }
  }
  </code></pre>