How can I resize QMessageBox?
You can subclass QMessageBox
and reimplement resize event handler as following:
void MyMessageBox::resizeEvent(QResizeEvent *Event)
{
QMessageBox::resizeEvent(Event);
this->setFixedWidth(myFixedWidth);
this->setFixedHeight(myFixedHeight);
}
I wanted my QMessageBox width to adapt in proportion to the length of the text content with a certain amount of buffer to avoid line wrap. After surveying numerous forums and threads including this one, I came up with:
int x_offset = (2.0 * MainWindow::geometry().x());
int y_offset = (0.5 * MainWindow::geometry().y());
msgBox.setText(vers_msg.data());
QSpacerItem* horizontalSpacer = new QSpacerItem
(8 * vers_msg.size(), 0,
QSizePolicy::Minimum, QSizePolicy::Expanding);
QGridLayout* layout = (QGridLayout*)msgBox.layout();
layout->addItem(horizontalSpacer, layout->rowCount(),
0, 1, layout->columnCount());
msgBox.setGeometry(
MainWindow::geometry().x() + x_offset,
MainWindow::geometry().y() + y_offset,
msgBox.geometry().width(),
msgBox.geometry().height());
Adjust the hard numbers in x_offset, y_offset and horizontalSpacer to suit your situation. I was hoping it would be easier than this but at least this works.
You can edit the css of the label:
msg.setStyleSheet("QLabel{min-width: 700px;}");
You can similarly edit the css of the buttons to add a margin or make them bigger.
For example:
msg.setStyleSheet("QLabel{min-width:500 px; font-size: 24px;} QPushButton{ width:250px; font-size: 18px; }");
There is also a trick mentioned:
QSpacerItem* horizontalSpacer = new QSpacerItem(800, 0, QSizePolicy::Minimum, QSizePolicy::Expanding);
QGridLayout* layout = (QGridLayout*)msg.layout();
layout->addItem(horizontalSpacer, layout->rowCount(), 0, 1, layout->columnCount());
But this doesn't seem to work for everyone.
coyotte508's answer caused my layout to be horribly off center and at different widths it was cut off. In searching around further I found this thread which explains a better solution.
In essence the layout of a messagebox is a grid, so you can add a SpacerItem to it to control the width. Here's the c++ code sample from that link:
QMessageBox msgBox;
QSpacerItem* horizontalSpacer = new QSpacerItem(500, 0, QSizePolicy::Minimum, QSizePolicy::Expanding);
msgBox.setText( "SomText" );
QGridLayout* layout = (QGridLayout*)msgBox.layout();
layout->addItem(horizontalSpacer, layout->rowCount(), 0, 1, layout->columnCount());
msgBox.exec();