gpt4 book ai didi

PYQT QSplitter问题

转载 作者:行者123 更新时间:2023-12-04 00:04:29 31 4
gpt4 key购买 nike

我使用 QSplitter,我发现小部件的最小宽度在拆分器为 32 像素(高度为 23 像素)。有没有人知道如何更改此默认值。换句话说,您不能拖动拆分器,以便其中一个spllitter中的widgets(假设spllitter中有2个widgets)会更少宽度不超过 32 像素。

代码:

class Example(QtGui.QWidget):

def __init__(self):
super(Example, self).__init__()
self.initUI()

def initUI(self):

self.resize(400,400)

m = QtGui.QSplitter(self)
m.resize(200, 100)

x = QtGui.QPushButton(m)
x.setGeometry(0, 0, 100, 100)

y = QtGui.QPushButton(m)
y.setGeometry(0, 100, 100, 100)


m.setSizes([20, 180])
# this will show you that the width of x is 32 (it should be 20!)
print x.width()

最佳答案

注意:我使用的是 Python 3.6.2 和 PyQt5,尽管示例中的逻辑保持不变,即使您使用其他版本的 Python 和 PyQt 也可以理解。

看看是怎么说的here:

If you specify a size of 0, the widget will be invisible. The size policies of the widgets are preserved. That is, a value smaller than the minimal size hint of the respective widget will be replaced by the value of the hint.

解决问题的方法之一是调用 x.setMinimumWidth() 一个小的值,例如:

x.setMinimumWidth(1)

不过,如果你自己尝试一下,你就会明白

  1. 这是一个肮脏的 hack,因为它实际上将小部件留在这里,只是让它变得非常窄
  2. 虽然现在您可以拖动分隔条,但小部件的初始宽度仍然是“32”而不是“20”。

x.setMinimumWidth(0)

也没有按预期工作:它的最小宽度实际上默认为零(我猜是因为这个小部件没有内容),但它没有帮助您使分隔项宽度小于 32 像素,除非您折叠它。

顺便说一下

m.setCollapsible(0, False)
m.setCollapsible(1, False)

如果您希望 splitter 停止折叠它的两个子部件。更多详情 here.

我找到的解决方案是重载要包含到拆分器中的小部件的 sizeHint() 方法,如下例所示(查看 ButtonWrapper类以及现在的输出)。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Python 3.6.2 and PyQt5 are used in this example


from PyQt5.QtWidgets import (
QPushButton,
QSplitter,
QWidget,
QApplication,
)

import sys


class ButtonWrapper(QPushButton):

def sizeHint(self):

return self.minimumSize()


class Example(QWidget):

def __init__(self):

super().__init__()
self.initUI()

def initUI(self):

self.resize(400, 400)

m = QSplitter(self)
m.resize(200, 100)

x = ButtonWrapper(self)
x.setGeometry(0, 0, 100, 100)

y = QPushButton(self)
y.setGeometry(0, 100, 100, 100)

m.addWidget(x)
m.addWidget(y)

m.setSizes([20, 180])

#Now it really shows "20" as expected
print(x.width())

#minimumWidth() is zero by default for empty QPushButton
print(x.minimumWidth())

#Result of our overloaded sizeHint() method
print(x.sizeHint().width())
print(x.minimumSizeHint().width())

self.setWindowTitle('Example')
self.show()


if __name__ == '__main__':

app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())

我不确定这是否是正确的做事方式,但我花了很多时间尝试解决与此相关的我自己的问题,但到目前为止还没有看到任何令人满意的东西。如果有人知道更好的实际有效且清晰解决方法,我将不胜感激。

关于PYQT QSplitter问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7167929/

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