Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centre widget on parent widget without layout

I am adding a widget to a parent widget without the use of a layout (because I'm using some animations that conflict with what the layout try to do).

I am trying to understand what I need to do to align the child widget to it's parent manually (centre it horizontally and vertically even when the parent widget is resized).

I've tried calculating the position myself and using QWidget.move() and QWidget.setGeometry(), but neither worked properly as I seem to be unable to get the correct parent width and height.

Here is a simplified example of what I'm trying to achieve:

import sys
from PySide.QtGui import *
from PySide.QtCore import *

class Test( QWidget ):

    def __init__( self, parent=None ):
          super( Test, self ).__init__( parent )

    def sizeHint( self ):
        return QSize( 500, 500 )

    def addPage( self, widget ):
        widget.setParent( self )
        # THIS SEEMS UNPREDICTABLE:
        widget.move( self.sizeHint().width()/2, self.sizeHint().height()/2 ) 

if __name__ == '__main__':
    app = QApplication( sys.argv )

    mainW = Test()
    childW = QPushButton( 'centre me please' )
    mainW.addPage( childW )
    mainW.show()

    sys.exit( app.exec_() )
like image 903
Frank Rueter Avatar asked Jan 23 '26 13:01

Frank Rueter


1 Answers

You can use QWidget.setGeometry to place your child widget at the centre. If you want it to stay that way no matter what happens to your main widget, then you need to catch events corresponding to the changes you expect.

The following should work:

#!/usr/bin/env python


from PyQt4 import QtGui, QtCore
import sys

class Application(QtGui.QApplication):

    def __init__(self):
        QtGui.QApplication.__init__(self, sys.argv)

        self.main = MyWidget()
        self.main.show()


class MyWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QLabel.__init__(self, parent)

        self.setStyleSheet("QWidget { background-color : white}")
        self.setGeometry(0, 0, 200, 200)

        self.sub_widget = QtGui.QWidget(self)
        self.sub_widget.setStyleSheet("QWidget { background-color : black}")
        self.sub_widget.setGeometry((self.width()-100)/2, (self.height()-100)/2 , 100, 100)

    def resizeEvent(self, event):

        self.sub_widget.setGeometry((self.width()-100)/2, (self.height()-100)/2 , 100, 100)
like image 109
neydroydrec Avatar answered Jan 25 '26 02:01

neydroydrec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!