c++ - 从代码创建的 QPushButton 的最小尺寸/宽度

标签 c++ qt button resize

我创建了 2 行按钮,每行都在 QHBoxLayout 中。 enter image description here

我在代码中创建按钮:

static const char* buttonText = "23456789TJQKA";
for (int ii = 0; buttonText[ii]; ii++)
{
    QPushButton* pushButton = new QPushButton(this);
    pushButton->setText(QString(buttonText[ii]));
    ui->horizontalLayout_1->addWidget(pushButton);
}
for (int ii = 0; buttonText[ii]; ii++)
{
    QPushButton* pushButton = new QPushButton(this);
    pushButton->setText(QString(buttonText[ii]));
    ui->horizontalLayout_2->addWidget(pushButton);
}

问题是它们不能缩小(当用户调整对话框大小时)超过该尺寸,即使它们的文本适合更小的宽度。如果我在资源编辑器中而不是在代码中手动创建按钮,它们的宽度可以比这更小。

最佳答案

发生这种情况是因为QPushButtonminimumSizeHint 不允许QLayout 调整它的大小:

The default implementation of minimumSizeHint() returns an invalid size if there is no layout for this widget, and returns the layout's minimum size otherwise. Most built-in widgets reimplement minimumSizeHint().

QLayout will never resize a widget to a size smaller than the minimum size hint unless minimumSize() is set or the size policy is set to QSizePolicy::Ignore. If minimumSize() is set, the minimum size hint will be ignored.

简单的解决方案是显式设置最小宽度:

static const char* buttonText = "23456789TJQKA";
for (int ii = 0; buttonText[ii]; ii++)
{
   QPushButton* pushButton = new QPushButton(this);
   pushButton->setMinimumWidth(5);
   pushButton->setText(QString(buttonText[ii]));
   ui->horizontalLayout_1->addWidget(pushButton);
}
for (int ii = 0; buttonText[ii]; ii++)
{
   QPushButton* pushButton = new QPushButton(this);
   pushButton->setMinimumWidth(5);
   pushButton->setText(QString(buttonText[ii]));
   ui->horizontalLayout_2->addWidget(pushButton);
}

关于c++ - 从代码创建的 QPushButton 的最小尺寸/宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6639012/

相关文章:

css - 使用 CSS sprites 设置按钮背景图像、按钮图标图像和文本的样式

java - ANDROID 如何检查两个按钮是否同时保持在一起?

JavaScript 函数未运行

C++在Linux中获取源文件目录

c++ - 如何在存储指针的容器中查找整数?

c++ - undefined reference EVP_sha1 、HMAC、Id 返回 1 退出状态

c++ - Qt - 重新实现 QIODevice 以实时听到我自己的声音

c++ - 指针引用模式 - 常用?

c++ - 在 Vim 中加载 google.vim 缩进文件

c++ - 如何中止加载程序中的加载组件?