gpt4 book ai didi

python - 带有 QSizePolicy.Expanding 的 setSizePolicy() 不起作用 : the child does not expand to the size of the parent

转载 作者:行者123 更新时间:2023-12-05 03:02:59 24 4
gpt4 key购买 nike

根据 http://doc.qt.io/qt-5/qsizepolicy.html#Policy-enum ,设置小部件的大小策略具有以下效果:

The sizeHint() is a sensible size, but the widget can be shrunk and still be useful. The widget can make use of extra space, so it should get as much space as possible (e.g. the horizontal direction of a horizontal slider).

因此,我希望下面的黄色小部件填满绿色小部件,但并没有发生。我做错了什么?

enter image description here

import sys

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class Yellow(QWidget):

def __init__(self, *args):
super().__init__(*args)

# Set palette
bg = QPalette()
bg.setColor(QPalette.Window, Qt.yellow)
self.setAutoFillBackground(True)
self.setPalette(bg)

self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

class Green(QWidget):

def __init__(self, *args):
super().__init__(*args)

# Set palette
bg = QPalette()
bg.setColor(QPalette.Window, Qt.green)
self.setAutoFillBackground(True)
self.setPalette(bg)

self.yellow = Yellow(self)

class App(QMainWindow):

def __init__(self):
super().__init__()
self.title = 'PyQt5'
self.left = 10
self.top = 10
self.width = 200
self.height = 200
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

self.green = Green(self)
self.green.resize(184, 154)
self.green.move(10, 10)

self.show()

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

ex = App()
sys.exit(app.exec_())

最佳答案

使用布局:

class Green(QWidget):

def __init__(self, *args):
super().__init__(*args)

# Set palette
bg = QPalette()
bg.setColor(QPalette.Window, Qt.green)
self.setAutoFillBackground(True)
self.setPalette(bg)

self.yellow = Yellow(self)
self.myLayout = QGridLayout()
self.myLayout.addWidget(self.yellow)
self.setLayout(self.myLayout)

结果:

result

如果添加 self.myLayout.setContentsMargins(0,0,0,0) 黄色小部件完全覆盖绿色小部件:

result2

关于python - 带有 QSizePolicy.Expanding 的 setSizePolicy() 不起作用 : the child does not expand to the size of the parent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54276638/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com