我目前正在处理一个应用程序的本地化。一切都按照我的预期进行了翻译,但是,QMessageBox
没有调整按钮的大小以适应文本。
这是我用来生成问题框的代码,QTranslator
包含在定义 MM_TR
的地方:
#include <QMessageBox>
void MainWindow::closeEvent( QCloseEvent * pEvent ) {
QMessageBox::StandardButtons iButtons = QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel;
QMessageBox::StandardButton iDefaultButton = QMessageBox::Save;
QMessageBox::StandardButton iButton = QMessageBox::question( this, QString::fromStdString( MM_TR( "ctxMessageBoxQuestion", "Save changes?" ) ), QString::fromStdString( MM_TR( "ctxMessageBoxQuestion", "Project has been modified, save changes?" ) ), iButtons, iDefaultButton );
}
我在互联网上搜索过任何遇到同样问题的人,但到目前为止还没有找到任何结论。我已经尝试将大小策略设置为 Minimum
和 MinimumExpanding
但这也不起作用。唯一可行的是设置样式表,我尝试使用以下代码:
QMessageBox::StandardButtons iButtons = QMessageBox::Save | QMessageBox::Abort | QMessageBox::Cancel;
QMessageBox msgClose( QMessageBox::Question, "Test", "Test button translation resizing.", iButtons );
msgClose.setStyleSheet( "QPushButton {min-width:100;}" );
不过,我不认为正确的做法是根据出现的任何语言手动设置最小宽度,所以我不想那样做。这也会为所有按钮更改它,这不是我想要的。
我想知道此时是否唯一的选择是创建自定义对话框?
更新: 我的最终解决方案包括 cbuchart的答案以及样式表填充设置:
QMessageBox::StandardButtons iButtons = QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel;
QMessageBox msgClose( QMessageBox::Question, QString::fromStdString( MM_TR( "ctxMessageBoxQuestion", "Save changes?" ) ), QString::fromStdString( MM_TR( "ctxMessageBoxQuestion", "Project has been modified, save changes?" ) ), iButtons );
msgClose.setStyleSheet( "QPushButton {padding: 3px;}" );
msgClose.layout()->setSizeConstraint( QLayout::SizeConstraint::SetMinimumSize );
QMessageBox::StandardButton iButton = (QMessageBox::StandardButton)msgClose.exec();
需要注意的是,如果 padding 增加太多,它会开始覆盖文本 - 我不太明白 - 但 3px 似乎不错。
更新 2:
在尝试之后,我认为 QMessageBox
有一些固定的宽度,它链接到无法修改的消息框文本本身。如果消息框文本足够长,按钮会调整大小并适合按钮文本,因此看起来按钮大小调整与按钮文本本身无关。
我尝试使用 setMinimumWidth
和 setFixedWidth
进行调整,但框没有调整大小。基于此错误中的评论 QTBUG-7851 ,我认为 QMessageBox
不能以编程方式调整大小。如果有人知道不包括制作自定义对话框的实际解决方案,那就太好了。
更新 3:
根据 cbuchart 的评论,我意识到有一个 .qss 样式表的 min-width
设置导致 QPushButton
无法正确调整大小。
最佳答案
不需要使用样式表,尽管您仍然需要手动创建对象而不是使用 QMessageBox::question
。
您可以使用 QLayout::setSizeConstraint
将消息框布局更改为自动展开.这将强制对话框调整大小以适合其内容。
例子(也可以找到here):
#include <QtWidgets/QApplication>
#include <qmessagebox.h>
#include <qlayout.h>
int main(int argc, char* argv[])
{
QApplication a(argc, argv);
QMessageBox::StandardButtons iButtons = QMessageBox::Save | QMessageBox::Abort | QMessageBox::Cancel;
QMessageBox msgClose( QMessageBox::Question, "Test", "Test button translation resizing.", iButtons );
msgClose.setButtonText(QMessageBox::Save, "Save: super mega long text for testing");
msgClose.setButtonText(QMessageBox::Cancel, "Cancel: another super mega long text for testing");
msgClose.layout()->setSizeConstraint(QLayout::SetMinimumSize); // QLayout::SetFixedSize also works
msgClose.exec();
return 0;
}
关于c++ - 如何调整 QMessageBox 按钮的大小以适应翻译后的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51679073/