在没有布局的父小部件上居中小部件 [英] Centre widget on parent widget without layout

查看:44
本文介绍了在没有布局的父小部件上居中小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在不使用布局的情况下将小部件添加到父小部件(因为我使用了一些与布局尝试执行的操作冲突的动画).

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).

我尝试自己计算位置并使用 QWidget.move()QWidget.setGeometry(),但两者都无法正常工作,因为我似乎无法获取正确的父级宽度和高度.

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

推荐答案

您可以使用 QWidget.setGeometry 将您的子部件放置在中心.如果您希望无论您的主要小部件发生什么事情都保持这种状态,那么您需要捕捉与您期望的更改相对应的事件.

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.

以下应该有效:

#!/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)

这篇关于在没有布局的父小部件上居中小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆