如何调整布局内按钮的排列方向?实现QVBoxLayout按钮从下到上排布
实现方案
如果你只是需要按钮在左侧垂直方向从下到上排列、文字保持横向,直接调整布局属性即可,不需要旋转按钮:
- 首先确认你用的是垂直布局
QVBoxLayout,水平布局QHBoxLayout才会默认从左到右排列控件 - 给
QVBoxLayout设置底部对齐属性,添加的按钮就会自动从下往上依次排布
PyQt/PySide示例代码:
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QHBoxLayout from PyQt5.QtCore import Qt class DemoWindow(QWidget): def __init__(self): super().__init__() # 主布局用水平布局,区分左侧按钮区和右侧内容区 main_layout = QHBoxLayout(self) # 左侧按钮区布局 left_btn_layout = QVBoxLayout() left_btn_layout.addWidget(QPushButton("按钮1")) left_btn_layout.addWidget(QPushButton("按钮2")) left_btn_layout.addWidget(QPushButton("按钮3")) # 关键设置:布局内容靠底部对齐,实现从下到上排列 left_btn_layout.setAlignment(Qt.AlignBottom) main_layout.addLayout(left_btn_layout) # 右侧添加其他内容控件即可 main_layout.addWidget(QWidget())
C++ Qt对应核心代码为:
QVBoxLayout *leftBtnLayout = new QVBoxLayout; leftBtnLayout->addWidget(new QPushButton("按钮1")); leftBtnLayout->addWidget(new QPushButton("按钮2")); leftBtnLayout->addWidget(new QPushButton("按钮3")); leftBtnLayout->setAlignment(Qt::AlignBottom);
如果你需要按钮文字纵向显示、减少侧边栏的宽度占用,你提到的旋转90度是非常常规的实现方案,没有兼容性问题,自定义旋转按钮类即可:
from PyQt5.QtWidgets import QPushButton from PyQt5.QtGui import QPainter class VerticalButton(QPushButton): def paintEvent(self, event): QPushButton.paintEvent(self, event) painter = QPainter(self) painter.rotate(-90) painter.drawText(-self.height(), self.width()/2, self.text())
需求效果示意图:
内容的提问来源于stack exchange,提问作者Leo Odriozola
相关产品推荐
相关产品推荐

