我试图找到一种方法让我的一个小部件根据其高度保持宽度。我有其他的小部件可以很好地重新实现heightForWidth方法。这很简单,因为这种方法是标准的。我知道没有包含widthForHeight的方法,所以我尝试了很多互联网上建议的方法,但一直没有得到任何效果。我现在所拥有的几乎能让我达到目的。在
我首先重新实现widget的sizeHint,使其宽度与其父控件(QHBoxLayout)的高度成比例。在
sizeHint使MyCustomLabel在第一次显示时具有正确的大小,但在用户调整窗口大小时不会更新。我不知道这是否是最好的方法,但是为了解决这个问题,我正在重新实现resizeEvent并调用adjustSize来强制重新计算sizeHint。在
通过这两个重新实现的方法,MyCustomLabel显示的大小是正确的。我把这个定制的小部件放在一个QHBoxLayout中,还有一些其他的标准部件。问题是当用户调整窗口大小时,布局中的其他小部件不考虑MyCustomLabel的新大小。最后,我发现布局中的其他小部件要么重叠,要么放置在离MyCustomLabel太远的地方。我有点明白了,我很粗暴地强迫我的小部件到一个大小,而不让布局做工作。不过,我认为更新sizeHint会通知MyCustomLabel的新大小的布局,并相应地调整所有内容。我该怎么解决这个布局问题呢?还是说我的宽度对高度的问题完全错了?在
编辑: 我尝试了@AlexanderVX将SizePolicy设置为最小值的建议,虽然它确实可以防止其他小部件重叠,但它也将MyCustomLabel锁定为固定大小。我需要小部件来扩展和缩小布局。我还尝试了优先、扩展、最小扩展的策略,只是想看看它们是否能做些什么,但没有运气。在
from __future__ import division
from PySide import QtCore
from PySide import QtGui
import sys
class MyCustomLabel(QtGui.QLabel):
clicked = QtCore.Signal(int)
dblClicked = QtCore.Signal(int)
def __init__(self, leadSide='height', parent=None):
super(MyCustomLabel, self).__init__()
self.leadSide = leadSide
# sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred,
# QtGui.QSizePolicy.Preferred)
# sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,
# QtGui.QSizePolicy.Expanding)
# sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.MinimumExpanding,
# QtGui.QSizePolicy.MinimumExpanding)
# sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum,
# QtGui.QSizePolicy.Minimum)
# self.setSizePolicy(sizePolicy)
def resizeEvent(self, event):
super(MyCustomLabel, self).resizeEvent(event)
self.adjustSize()
def sizeHint(self):
super(MyCustomLabel, self).sizeHint()
parentSize = self.parent().size().toTuple()
if self.leadSide.lower() == 'height':
new_size = QtCore.QSize(parentSize[1] * (16 / 9), parentSize[1]) * .9
if self.leadSide.lower() == 'width':
new_size = QtCore.QSize(parentSize[0], parentSize[0] / (16 / 9)) * .9
return new_size
class __Test__(QtGui.QWidget):
def __init__(self):
super(__Test__, self).__init__()
self.initUI()
def initUI(self):
customLabel = MyCustomLabel(leadSide='height')
# customLabel.setScaledContents(True)
customLabel.setStyleSheet('background-color: blue;'
'border:2px solid red;')
btn01 = QtGui.QPushButton('button')
btn01.setFixedHeight(80)
textEdit = QtGui.QTextEdit()
textEdit.setFixedSize(150, 150)
layout01 = QtGui.QHBoxLayout()
layout01.setContentsMargins(0,0,0,0)
layout01.setSpacing(0)
layout01.addWidget(customLabel)
layout01.addWidget(btn01)
layout01.addWidget(textEdit)
self.setLayout(layout01)
self.setGeometry(300, 300, 600, 300)
self.setWindowTitle('Testing')
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = __Test__()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
目前没有回答
相关问题 更多 >
编程相关推荐