这有点令人沮丧,但我找不到设置 QPushButton 大小的正确方法。根据我的阅读,我认为这段代码应该有效:
// SEND BUTTON
sendButton = new QPushButton(this);
sendButton->setText("Send");
sendButton->setMinimumSize(QSize(0,0));
sendButton->setMaximumSize(QSize(10000,10000));
sendButton->setGeometry(QRect(QPoint(30, 100),QSize(10, 20)));
connect(sendButton, &QPushButton::released, this, &MainWindow::handleSendButton);
// CENTRAL WIDGET
QWidget* centralWidget = new QWidget(this);
centralWidget->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
// LAYOUT
QGridLayout* layout = new QGridLayout(centralWidget);
layout->addWidget(sendButton,0,0,0,0);
但是按钮总是扩展到整个应用程序窗口。你能帮忙吗?
最佳答案
Widget 的默认策略是QSizePolicy::Preferred
,但在您的情况下您应该使用QSizePolicy::Fixed
。
QSizePolicy::Preferred: The sizeHint() is best, but the widget can be shrunk and still be useful. The widget can be expanded, but there is no advantage to it being larger than sizeHint() (the default QWidget policy).
QSizePolicy::Fixed: The QWidget::sizeHint() is the only acceptable alternative, so the widget can never grow or shrink (e.g. the vertical direction of a push button).
此外,您必须建立要居中的对齐方式,以便从上面得到以下内容:
sendButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(sendButton,0,0,0,0, Qt::AlignCenter);
关于c++ - Qt5:QPushButon大小设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46193762/