要使按钮居中,可以在布局中使用 QHBoxLayout
来将按钮放置于一个水平布局中,并将其添加到垂直布局的底部。下面是修改后的代码,使按钮居中:
#include <QApplication>
#include <QDialog>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QRadioButton>
#include <QPushButton>
#include <QMessageBox>
class MyDialog : public QDialog {
Q_OBJECT
public:
MyDialog(QWidget *parent = nullptr) : QDialog(parent) {
// 设置对话框的固定大小
setFixedSize(300, 150); // 宽度300,高度150
// 创建垂直布局
QVBoxLayout *layout = new QVBoxLayout(this);
// 创建单选按钮
QRadioButton *radio1 = new QRadioButton("选项 1", this);
QRadioButton *radio2 = new QRadioButton("选项 2", this);
// 添加单选按钮到布局
layout->addWidget(radio1);
layout->addWidget(radio2);
// 创建一个水平布局来居中按钮
QHBoxLayout *hLayout = new QHBoxLayout();
// 创建提交按钮
QPushButton *submitBtn = new QPushButton("提交", this);
// 将提交按钮添加到水平布局并设置居中
hLayout->addStretch(); // 添加弹性空间以推送内容向中心
hLayout->addWidget(submitBtn);
hLayout->addStretch(); // 添加弹性空间以推送内容向中心
// 将水平布局添加到垂直布局
layout->addLayout(hLayout);
connect(submitBtn, &QPushButton::clicked, [=]() {
if (radio1->isChecked()) {
QMessageBox::information(this, "选择", "你选择了: 选项 1");
} else if (radio2->isChecked()) {
QMessageBox::information(this, "选择", "你选择了: 选项 2");
} else {
QMessageBox::warning(this, "选择", "请至少选择一个选项!");
}
accept(); // 确认对话框并关闭
});
setLayout(layout);
}
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
MyDialog dialog;
dialog.setWindowTitle("单选按钮对话框");
dialog.exec();
return app.exec();
}
#include "main.moc"
更新部分说明:
- 使用
QHBoxLayout
来创建一个新的横向布局hLayout
。 - 在这个横向布局中,使用
addStretch()
方法在提交按钮之前和之后添加弹性空间,这样可以使提交按钮居中显示。
这样,”提交” 按钮将在窗口底部居中。
内容由零声教学AI助手提供,问题来源于学员提问