views:

1655

answers:

4

The application I'm working on has a custom UI that required me to remove the title bar from the main window. Unfortunately, I can't figure out how to make it so I can move the application on the screen :)

The code I have which is removing the title bar is the following:

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent, Qt::CustomizeWindowHint), ui(new Ui::MainWindowClass)
{
    ui->setupUi(this);

Any idea how I can move the window around using either another widget or the main form window itself?

Thanks

+4  A: 

Most intuitive way to do this would be clicking on the widget surface and dragging. In order to achieve this, you need to follow some steps.

The method goes as follows: When the user presses inside the widget, set a boolean flag and store the position of the mouse and then when the button is released, set it to false. The next step is moving the widget. In the mouseMoveEvent, check if the flag is set. If it is set, take the new position of the mouse. Calculate the difference between new position and the stored one. Then, set the position of the window to original position + the calculated mouse movement. Then store the new mouse position.

The code required would be this:

/// Header contents:
class MyWidget : public QMainWindow
{
protected:
    void mouseMoveEvent(QMouseEvent* event);
    void mousePressEvent(QMouseEvent* event);
    void mouseReleaseEvent(QMouseEvent* event);
private:
    QPoint mLastMousePosition;
    bool mMoving;
}
/// Source:
void MyWidget::mousePressEvent(QMouseEvent* event)
{
    if(event->button() == Qt::LeftButton)
    {
     mMoving = true;
     mLastMousePosition = event->pos();
    }
}

void MyWidget::mouseMoveEvent(QMouseEvent* event)
{
    if( event->buttons().testFlag(Qt::LeftButton) && mMoving)
    {
     this->move(this->pos() + (event->pos() - mLastMousePosition));
     mLastMousePosition = event->pos();
    }
}

void MyWidget::mouseReleaseEvent(QMouseEvent* event)
{
    if(event->button() == Qt::LeftButton)
    {
     mMoving = false;
    }
}
erelender
See also Qt's shaped clock example, which does the same thing: http://doc.trolltech.com/4.5/widgets-shapedclock.html
Caleb Huitt - cjhuitt
A: 

I think this should also answer your question http://qt.nokia.com/developer/faqs/535

kriskarth
A: 

There is a typing error in erelender's answer.

The second "void MyWidget::mousePressEvent(QMouseEvent* event)" should be "void MyWidget::mouseMoveEvent(QMouseEvent* event)".

BTW, I suggest using "event->globalPos()" instead "event->pos()".

Sibevin Wang
Thanks for pointing out, i corrected the typing error.
erelender
A: 

What if I don’t want to reimplement functionality already there?

What if I want to use native functions in order to use KWin- or Aero-Snap?

There must be a way.

flying sheep