qt 创建一个包含两按钮,且安装和自定义控件间没有间距

在 Qt 中创建一个包含两个按钮且按钮之间没有间距的自定义控件,你可以使用 QHBoxLayoutQVBoxLayout(取决于你希望按钮是水平排列还是垂直排列),并设置布局的间距为 0。以下是一个简单的示例,展示了如何创建一个水平布局,其中包含两个按钮,并且这两个按钮之间没有间距:

|---|-----------------------------------------------------------|
| | #include <QWidget> |
| | #include <QPushButton> |
| | #include <QHBoxLayout> |
| | |
| | // ... |
| | |
| | QWidget *createCustomWidget() { |
| | QWidget *customWidget = new QWidget; |
| | QHBoxLayout *layout = new QHBoxLayout(customWidget); |
| | |
| | // 设置布局间距为0 |
| | layout->setSpacing(0); |
| | layout->setContentsMargins(0, 0, 0, 0); // 设置布局的外边距也为0 |
| | |
| | QPushButton *button1 = new QPushButton("Button 1"); |
| | QPushButton *button2 = new QPushButton("Button 2"); |
| | |
| | layout->addWidget(button1); |
| | layout->addWidget(button2); |
| | |
| | return customWidget; |
| | } |
| | |
| | // ... |

在这个例子中,createCustomWidget 函数创建了一个新的 QWidget,并使用 QHBoxLayout 作为其布局。布局中的间距和外边距都被设置为 0,以确保按钮之间以及按钮和控件边界之间没有额外的空间。然后,两个 QPushButton 控件被添加到布局中。

你可以在你的主窗口或者其他容器中使用这个自定义控件。例如,你可以在你的主窗口的构造函数中这样使用它:

|---|--------------------------------------------------------------------|
| | #include "mainwindow.h" |
| | #include <QApplication> |
| | #include <QWidget> |
| | #include <QPushButton> |
| | #include <QHBoxLayout> |
| | |
| | MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { |
| | QWidget *centralWidget = new QWidget(this); |
| | setCentralWidget(centralWidget); |
| | |
| | QWidget *customControl = createCustomWidget(); |
| | centralWidget->setLayout(new QVBoxLayout); |
| | centralWidget->layout()->addWidget(customControl); |
| | } |
| | |
| | // ... |
| | // 之前定义的 createCustomWidget 函数 |
| | // ... |

在这个例子中,MainWindow 的中心部件被设置为一个新的 QWidget,它使用 QVBoxLayout 作为布局。然后,将之前创建的自定义控件添加到这个布局中。这样,主窗口就会显示两个紧密相连的按钮,它们之间没有间距。

相关推荐
怀旧,20 小时前
【C++】20. unordered_set和unordered_map
开发语言·c++
alibli20 小时前
一文学会CMakeLists.txt: CMake现代C++跨平台工程化实战
开发语言·c++·系统架构
Florence2321 小时前
GPU硬件架构和配置的理解
开发语言
李游Leo21 小时前
JavaScript事件机制与性能优化:防抖 / 节流 / 事件委托 / Passive Event Listeners 全解析
开发语言·javascript·性能优化
油炸自行车21 小时前
【Qt】Window环境下搭建Qt6、MSVC2022开发环境(无需提前安装Visual Studio)
qt·visual studio·qt6·msvc2022·qt creator 17.0
JJJJ_iii1 天前
【左程云算法09】栈的入门题目-最小栈
java·开发语言·数据结构·算法·时间复杂度
枫叶丹41 天前
【Qt开发】显示类控件(三)-> QProgressBar
开发语言·qt
Bear on Toilet1 天前
继承类模板:函数未在模板定义上下文中声明,只能通过实例化上下文中参数相关的查找找到
开发语言·javascript·c++·算法·继承
码猿宝宝1 天前
浏览器中javascript时间线,从加载到执行
开发语言·javascript·ecmascript
OEC小胖胖1 天前
App Router vs. Pages Router:我应该如何选择?
开发语言·前端·前端框架·web·next.js