我徒劳地尝试将按钮和文本居中对齐,两者都放置在布局中。
他自己被放置在一个 GroupBox 中。
我有这个代码:
// Initialization
QScrollArea *centralFrame = new QScrollArea();
QWidget *centralWidget = new QWidget;
QVBoxLayout *centerLayout = new QVBoxLayout();
QGroupBox *infoGroup = new QGroupBox();
QGridLayout *infoLayout = new QGridLayout();
QGroupBox *buttonGroup = new QGroupBox();
buttonGroup->setAlignment(Qt::AlignCenter);
QVBoxLayout *buttonLayout = new QVBoxLayout();
buttonLayout->setAlignment(Qt::AlignCenter);
QPushButton *userButton = new QPushButton();
centralWidget->setLayout(centerLayout);
// Set Styles
infoGroup->setStyleSheet("QGroupBox { background-color: #cfe2cf; border: 1px solid #1a651a; border-radius: 4px;} QLabel { color: #1d301d; }");
buttonGroup->setStyleSheet("QGroupBox { background-color: white; border: 1px solid #1a651a; border-radius: 4px;} QLabel { color: black; }");
// Defintion Bouton
userButton->setText("Select this User");
userButton->setStyleSheet("background-color: #dfdfdf; border: 1px solid #333333");
userButton->setMaximumWidth(110);
// Add Widgets at Button Group
buttonLayout->addWidget(userButton,Qt::AlignCenter);
buttonLayout->addWidget(new QLabel("Instructions for using the Button"),Qt::AlignCenter);
buttonGroup->setLayout(buttonLayout);
// Add Widgets at Infos Group
infoLayout->addWidget(new QLabel("Last Name : <b>QUIDAM</b>"));
infoLayout->addWidget(new QLabel("First Name : <b>Jean-Paul</b>"));
infoLayout->addWidget(buttonGroup);
// Set Layout and Frames
infoGroup->setLayout(infoLayout);
centerLayout->addWidget(infoGroup);
centralFrame->setWidget(centralWidget);
setCentralWidget(centralFrame);
我做错了什么......?
在@musicamante的帮助下,我找到了解决方案并回答了我自己的问题
我替换这个代码
// Defintion Bouton
userButton->setText("Select this User");
userButton->setStyleSheet("background-color: #dfdfdf; border: 1px solid #333333");
userButton->setMaximumWidth(110);
通过这段代码(用CSS定义按钮宽度)
// Defintion Bouton
userButton->setText("Select this User");
userButton->setStyleSheet("background-color: #dfdfdf; border: 1px solid #333333; width: 110px");
我替换了这个代码
// Add Widgets at Button Group
buttonLayout->addWidget(userButton,Qt::AlignCenter);
通过此代码(正确使用 addWidget 和 strech 参数)
// Add Widgets at Button Group
buttonLayout->addWidget(userButton,0,Qt::AlignCenter);
就像@musicamante 所说,我删除了这段代码
buttonGroup->setAlignment(Qt::AlignCenter);
希望这个问题和解决方案可以帮助到