【发布时间】:2019-02-19 21:31:32
【问题描述】:
这个问题让我发疯了,我似乎找不到合乎逻辑的答案。我对此很陌生,所以请多多包涵。
我一直在创建一个应用程序,在该应用程序中创建了一个垂直的“导航栏”,并且需要动态添加 QPushButtons。我注意到 在 QVBox 中添加 QPushButton 时,标签的水平位置会发生变化。
我创建了一个最小版本:
在添加 QPushButton 之前:
标签到达应用程序的边缘
添加QPushButton后:
标签宽度略微减小
这是我用来动态添加 QPushButton 的代码:
void MainWindow::on_pushButton_clicked()
{
QPushButton *newButton = new QPushButton("Test");
newButton->setContentsMargins(0,0,0,0);
newButton->setStyleSheet("margin: 0; padding: 0;");
ui->verticalLayout->setMargin(0);
ui->verticalLayout->setContentsMargins(0,0,0,0);
// add new push button inside VBox
ui->verticalLayout->addWidget(newButton);
}
.ui 文件:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>203</width>
<height>224</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralWidget">
<widget class="QWidget" name="verticalLayoutWidget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>201</width>
<height>151</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="label">
<property name="styleSheet">
<string notr="true">border: 1px solid white;</string>
</property>
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QPushButton" name="pushButton">
<property name="geometry">
<rect>
<x>10</x>
<y>180</y>
<width>181</width>
<height>32</height>
</rect>
</property>
<property name="text">
<string>Add Push Button To VBox</string>
</property>
</widget>
</widget>
</widget>
<layoutdefault spacing="6" margin="11"/>
<resources/>
<connections/>
</ui>
正如您所见,在 QPushButton 和布局上设置边距似乎没有任何效果。有没有人可以对这个问题有所了解?
【问题讨论】:
-
编辑了我的答案,希望对您有所帮助