我正在 Qt Designer 中创建一个新的 QWidget,其中包含一个 frame,其中包含一个 QLabel 和一个 QTextEdit。我可以设置所有这些元素的几何形状,并将它们设置为固定,这样它们的高度/宽度就不会改变:
在此示例中,我的QLabel 和QLineEdit 位于其父框架的右上角。如果我现在为框架设置布局(我需要这样做以确保元素在调整窗口大小时保持在正确的位置,或者如果框架是 QScrollArea 的主要小部件),那么元素被移动,甚至在框架的引用范围内:
在此实例中,表单布局应用于框架;我们可以看到 QLabel 的 (X,Y) 坐标已经从 (0,0) 变为 (10,10)。无论我是否事先将两个元素包装在垂直框架中,都会发生这种情况。
鉴于我正在尝试通过手动设置元素坐标来创建非常精确的布局,因此在应用布局时让它们移动看似随机的量非常令人沮丧。我该怎么办?!我想我误解了什么,但我不知道是什么!
请您参考如下方法:
布局具有默认边距和间距,其精确值由当前小部件样式提供。
您可以通过单击布局的父小部件并向下滚动到属性编辑器的底部来覆盖默认值,您将在其中看到具有相关值的布局部分 (-1 表示“使用默认值”)。
编辑:
有一件事我没有说清楚,就是布局边距和间距会在您每次中断和重置布局时恢复到默认值!这有时会很烦人,但确实有意义,因为每次执行此操作都会创建一个新布局。
无论如何,我认为问题的真正根源实际上是您使用的是表单布局,它比其他布局灵活得多。我认为你应该做的是将标签和行编辑放在水平布局中,最后有一个水平分隔符。然后在Horizontal Layout下面放一个Vertical Spacer,在Frame上添加一个Vertical Layout。这种安排将使标签和行编辑保持在框架的左上角。准备就绪后,您最终可以将垂直布局边距设置为零以获得所需的结果。
这是一个 .ui 文件,您可以对其进行测试以了解它们是如何组合在一起的:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>316</width>
<height>150</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QFrame" name="frame">
<property name="frameShape">
<enum>QFrame::StyledPanel</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="spacing">
<number>0</number>
</property>
<property name="margin">
<number>0</number>
</property>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="spacing">
<number>0</number>
</property>
<item>
<widget class="QLabel" name="label">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>75</width>
<height>0</height>
</size>
</property>
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>100</width>
<height>0</height>
</size>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>106</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>
