【Qt】按钮样式--按钮内部布局(调整按钮文本和图标放置在任意位置)

要求:

有一个按钮,要求按钮的右下角显示开关,点击切换开关状态

ps:注意,要求你添加完了之后,整个按钮的点击区域不变(就是说,点击右下角的文本,也可以触发按钮的点击事件,点击按钮中任何地方,都会触发点击事件,就是你在按钮上添加东西,不要影响按钮的点击区域)

效果:

实现:

将你要添加的东西,不管是label还是别的,都放在布局里,然后将按钮的布局设置一下就行。

我这个案例是添加了两个label

c++ 复制代码
    // 设置测试按钮
    testButton = new QPushButton("", this);
    testButton->setMinimumSize(QSize(420, 232));
    testButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    testButton->setProperty("TestButton",true);
    // 设置文字
    textLabel = new QLabel;
    textLabel->setProperty("TestButtonText", "start");
    textLabel->setText("running");
    textLabel->setFixedHeight(32);
    // 设置icon
    iconLabel = new QLabel;
    iconLabel->setFixedSize(32, 32);
    iconLabel->setScaledContents(true);// 强制图片填满label
    QPixmap _backgroundPixmap(":/img/start.png");
    iconLabel->setPixmap(_backgroundPixmap);
    // icon和文字布局
    QHBoxLayout* iconAndTextLayout = new QHBoxLayout();
    iconAndTextLayout->addStretch();
    iconAndTextLayout->addWidget(iconLabel);
    iconAndTextLayout->addWidget(textLabel);
    iconAndTextLayout->setSpacing(10);
    // 按钮布局
    QVBoxLayout* buttonLayout = new QVBoxLayout();
    buttonLayout->addStretch();
    buttonLayout->addLayout(iconAndTextLayout);
    testButton->setLayout(buttonLayout);
相关推荐
Rain的Java大神之路15 分钟前
Java后端用Vue3+TS独立闭环之后,MyBatis-Plus该退到哪一层?聊聊2026全栈效能的责任边界
java·后端·ai编程
Zenova EdgeOS32 分钟前
Go Redis 实战:工业边缘场景下的 go-redis
数据库·redis·golang·边缘计算·工业网关
比特屿32 分钟前
Spring AI 2.1实战(六):Tool Calling全链路,从@Tool 到人工确认
java·后端
海宇服务37 分钟前
零信任架构实战:基于海宇对外投资历史查询服务构建自动化供应商关联主体合规审查网关
java·人工智能·架构·自动化
我命由我1234538 分钟前
Android 广播 - Android 开机广播实现开机自启应用
android·java·linux·java-ee·kotlin·android studio·android-studio
stormsha1 小时前
`Could not create connection to database server`:MySQL 8 连不上,真凶藏在第 4 层
java·后端·mysql
荣码1 小时前
多模态应用入门:让AI看懂图片再回答问题,我踩了4个坑
java·python
2501_933923251 小时前
聚合查询与分组实战:从列筛选到行计算
数据库·mysql
用户072367066601 小时前
接口级配 50%、方法级配 30%,这个方法实际切多少
java·dubbo
淘源码A1 小时前
智能预问诊系统源码,基于SpringBoot、MyBatis-Plus、uni-app等技术栈,开箱即用
java·spring boot·源码·二次开发·电子病历·预问诊·智能预问诊