我如何获得在内部布局中的小部件尺寸
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我如何获得在内部布局中的小部件尺寸相关的知识,希望对你有一定的参考价值。
我在QWidget的布局中有一个QLabel,我尝试使用sizeHint
或geometry
,但是它不起作用。如何获得QLabel的实际宽度和高度?
from PySide2 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(689, 439)
self.horizontalLayout = QtWidgets.QHBoxLayout(Form)
self.horizontalLayout.setObjectName("horizontalLayout")
self.label = QtWidgets.QLabel(Form)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
self.label.setSizePolicy(sizePolicy)
self.label.setObjectName("label")
self.horizontalLayout.addWidget(self.label)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(QtWidgets.QApplication.translate("Form", "Form", None, -1))
self.label.setText(QtWidgets.QApplication.translate("Form", "TextLabel", None, -1))
import sys,os,asyncio
from PySide2 import QtWidgets
from PySide2.QtWidgets import (QApplication, QMainWindow, QMessageBox)
from qasync import QEventLoop, asyncSlot, asyncClose
from TestLB2 import Ui_Form
class LB(QtWidgets.QWidget, Ui_Form):
def __init__(self, *args, **kwargs):
super(LB, self).__init__(*args, **kwargs)
self.setupUi(self)
print(self.frameGeometry().width())
print(self.label.geometry().width())
print(self.label.sizeHint().width())
if __name__ == '__main__':
# mp.freeze_support()
app = QApplication(sys.argv)
loop = QEventLoop(app)
asyncio.set_event_loop(loop)
w = LB()
w.show()
sys.exit(app.exec_())
with loop:
loop.run_forever()
答案
出于效率方面的考虑,仅在必要时才更新几何属性,对于布局和小部件,它们仅在显示时才更新,因此无法获得所需的值。解决方案是在使用QTimer显示信息后立即获得该信息。
import asyncio
import os
import sys
from PySide2 import QtCore, QtWidgets
from qasync import QEventLoop, asyncSlot, asyncClose
from TestLB2 import Ui_Form
class LB(QtWidgets.QWidget, Ui_Form):
def __init__(self, *args, **kwargs):
super(LB, self).__init__(*args, **kwargs)
self.setupUi(self)
#
self.label.setStyleSheet("QLabel{background-color: red}")
QtCore.QTimer.singleShot(0, lambda: print(self.label.width()))
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
loop = QEventLoop(app)
asyncio.set_event_loop(loop)
w = LB()
w.show()
with loop:
loop.run_forever()
以上是关于我如何获得在内部布局中的小部件尺寸的主要内容,如果未能解决你的问题,请参考以下文章