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 作为布局。然后,将之前创建的自定义控件添加到这个布局中。这样,主窗口就会显示两个紧密相连的按钮,它们之间没有间距。

相关推荐
paterWang2 小时前
基于 Python 和 OpenCV 的酒店客房入侵检测系统设计与实现
开发语言·python·opencv
东方佑2 小时前
使用Python和OpenCV实现图像像素压缩与解压
开发语言·python·opencv
我真不会起名字啊3 小时前
“深入浅出”系列之杂谈篇:(3)Qt5和Qt6该学哪个?
开发语言·qt
laimaxgg3 小时前
Qt常用控件之单选按钮QRadioButton
开发语言·c++·qt·ui·qt5
牵牛老人3 小时前
Qt中使用QPdfWriter类结合QPainter类绘制并输出PDF文件
数据库·qt·pdf
水瓶丫头站住3 小时前
Qt的QStackedWidget样式设置
开发语言·qt
小钊(求职中)4 小时前
Java开发实习面试笔试题(含答案)
java·开发语言·spring boot·spring·面试·tomcat·maven
慕诗客5 小时前
QT基于Gstreamer采集的简单示例
开发语言·qt
Blasit5 小时前
C++ Qt建立一个HTTP服务器
服务器·开发语言·c++·qt·http
Victoria.a6 小时前
数组和指针常见笔试题(深度剖析)
c语言·开发语言