Search code examples
qtresizeqwidgetqt5.5

How to make a free space around a Frameless QWidget?


I have made a custom Window in Qt and now facing to resizing problem.

I want a free space around my QWidget (Qt::FramelessWindowHint) so i can process the Mouse Hover+Leave+press+release events in that area and in this events i change the cursor shape and resizing the widget. (I don't want mouseEvent for widget but for that space)

How could i get such area ?


Solution

  • I suppose your QWidget is added to a QLayout at some point. Then just ask the containing QLayout to reserve some free space around it's content by calling [setContentsMargins].

    Example, you had:

    QWidget* widget = new QWidget( parent );
    parent->layout()->addWidget( widget );
    

    Then, just add:

    parent->layout()->setContentsMargins( 100,100,100,100 );
    

    This will guarantee that widget has 100 pixels of empty area around it.

    To be more generic, and it case you had no parent, you can create an intermediate QWidget like that:

    You had:

    QWidget* myWidget = new QWidget( NULL );
    widget->show();
    

    Just do:

    QWidget* parentWithEmptySpaceBorder = new QWidget( NULL );
    parentWithEmptySpaceBorder->setLayout( new QVBoxLayout() );
    parentWithEmptySpaceBorder->layout()->setContentsMargins( 100,100,100,100 );
    
    QWidget* myWidget = new QWidget( NULL );
    parentWithEmptySpaceBorder->layout()->addWidget( myWidget );
    
    parentWithEmptySpaceBorder->show();