Centre widget on parent widget without layout

穿精又带淫゛_ 提交于 2019-12-08 12:06:12

问题


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_() )

回答1:


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)


来源:https://stackoverflow.com/questions/10719337/centre-widget-on-parent-widget-without-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!