One method that worked for me was to subclass QMessageBox and control the size with modified show and resize events:
TMessageBox::TMessageBox(
const QWidget *Parent)
:QMessageBox(const_cast<QWidget*>(Parent))
{
d_FixedWidth = 500;
this->setTextFormat(Qt::RichText);
this->setStyleSheet("dialogbuttonbox-buttons-have-icons: 0;nbutton-layout: 1;");
}
void TMessageBox::showEvent(
QShowEvent *Event)
{
QMessageBox::showEvent(Event);
this->setFixedWidth(d_FixedWidth);
}
void TMessageBox::resizeEvent(
QResizeEvent *Event)
{
QMessageBox::resizeEvent(Event);
this->setFixedWidth(d_FixedWidth);
}
I didn’t find another method that worked. I did find that the size must be set each time a resize or show event was received otherwise it would default back to whatever it decided to use.
I removed the fixed size completely about a year ago (I don’t remember exactly why but it was not because it didn’t work — there was some other reason). It is nice to have a constant look to the message boxes and not have them shrunk down to a minimum size.
Some other changes unrelated to your post …
The style sheet command in the constructor turns off the button icons and sets the format to OSX layout regardless of the platform it is run on (‘button-layout: 1;’). Probably not a good idea to force the button layout to something non-native but I always perferred the OSX version (with detailed text on left, options on right). I hate icons on buttons (on any software) so this was something I wanted to kill.
I use rich text for the members ‘setText’ and ‘setInformativeText’ so that it stands out a bit better. These member functions are subclassed to wrap the supplied text with RTF tags before passing to QMessageBox. Member ‘setText()’ is set to a larger bold font meant to have a very short description such as ‘Error Loading File’. Member ‘setInformativeText()’ has a bit more detail regarding whatever I am trying to comunicate such as ‘File ‘name.txt’ has an invalid entry’. The detailed text section of the messagebox, if used, contains all the details from the message and can contain quite a bit of text.
(Last updated: September 19, 2017)
A Google Search for «resize QMessageBox»
will show that I wasn’t alone in wanting to be able to resize a Qt5
QMessageBox. My main desire was to get the dialog to expand widthwise
more than it would by default, as shown above. When setting «informative
text» on the dialog, that text would end up getting wrapped very aggressively,
which looks bad when there’s file paths in there. See the above
screenshot for an example of what I mean. A short little PyQt script
to generate that dialog is here: qmessagebox.py
Or alternatively, here’s the code snippet:
box = QtWidgets.QMessageBox(self) box.setWindowTitle('Unable to load file') box.setText('Unable to load file') box.setInformativeText('[Errno 2] No such file or directory: foo/bar/baz/frotz/florb/nitfol') box.setStandardButtons(QtWidgets.QMessageBox.Ok) box.setDefaultButton(QtWidgets.QMessageBox.Ok) box.setIcon(QtWidgets.QMessageBox.Critical) return box.exec()
Now the QMessageBox implementation itself pretty thoroughly resists
attempts to set its size manually, or allow window resizing, or anything
along those lines. The usual QWidget size functions do nothing —
setMinimumSizeHint, setMinimumWidth, resize,
setSizePolicy, setFixedWidth — they’re all
useless. You can use setSizeGripEnabled to have the widget
draw a resize handle, but the window isn’t actually resizeable, so
that’s useless as well.
In terms of actual implementation inside QMessageBox itself, what’s
happening is that the widget will always get hard-resized to the width of
the main text attribute, and informativeText will always get word-wrapped
to that width whether you want it to or not.
Solution 1: Use setText() with newlines instead of setInformativeText()
In the end I came to believe that the
actual best solution is to just not use informativeText, and instead set
a regular text value which happens to include newlines. So
instead of the code above, you’d end up with a single line like this:
box.setText("Unable to load filenn[Errno 2] No such file or directory: foo/bar/baz/frotz/florb/nitfol")
You do have to be a bit careful if you’re potentially setting
longer bits of text this way, because the dialog could theoretically end up
much more wide than you want — even wider than your desktop in a
worst-case scenario. What I ended up doing in my own code was to use Python’s
built-in textwrap module to do it. This little snippet
ends up doing exactly what I’d wanted:
if infotext and infotext != '': text = "{}nn{}".format(message, "n".join(textwrap.wrap(infotext, width=100))) else: text = message msgbox.setText(text)
Solution 2: Don’t even use QMessageBox
Second-best, IMO, would be to eschew the use of QMessageBox entirely
and write your own QDialog-derived class to display things how you
want. This feels a little lame ’cause it seems like QMessageBox should be
able to cope with all this natively, but writing a simple dialog to mimic
its behavior but with more control over window sizing wouldn’t be very
difficult at all. I didn’t bother actually doing this once I realized I
could be using newlines in the text, as I’ve done above.
Solution 3: Playing games with the QMessageBox’s internal QLayout
There’s a few hits on Google suggesting this approach. QMessageBox has its
own internal Layout which it uses, and you can make alterations to that, or
its underlying objects. I wouldn’t really recommend this myself, because
the internal implementation of QMessageBox shouldn’t really be relied on to
stay stable from version to version. I’d suspect that it hasn’t actually
changed much in a long time, and it’d probably work out okay anyway, at least
for awhile. Still not something to be relied on, though.
Regardless, I had taken a look into this option and come up with a few
solutions here. The internal layout happens to be a QGridLayout, in a 3×3
configuration. The main «text» attribute is stored in the upper right
cell (row 0, column 2), and the «informativeText» attribute is stored
immediately below that (row 1, column 2). The last row is taken up by
a couple of QDialogButtonBoxes.
One thing which can be done here is to add in a new fixed-width widget to
the layout. You’d be able to do that with something like this:
layout = box.layout() widget = QtWidgets.QWidget() widget.setFixedSize(400, 1) layout.addWidget(widget, 3, 0, 1, 3)
… so you’d have a new fixed-width widget occupying a new row at the
bottom of the layout. Alternatively, you could dig into the layout
container itself and manually set a width on the main text attribute, which
would also make the dialog be wider:
layout = box.layout() item = layout.itemAtPosition(0, 2) widget = item.widget() widget.setFixedWidth(400)
The question at that point, though is what value to use for the width,
since you wouldn’t want to have a dialog with a bunch of empty space hanging
off the righthand side. That could actually be theoretically computed pretty
easily using the QFontMetrics class — something like this should do the
trick:
width = QtGui.QFontMetrics(QtGui.QFont()).boundingRect('informative text').width()
You’d probably need to make sure that you’re using an approprate QFont
object which represents the font being used on the dialog too, though.
In the end, that’s an awful lot of work against an internal structure
which could go away at any point without warning. I think either
of the first two solutions are much better.
Changelog
September 19, 2017
- Initial Post
9 / 9 / 1 Регистрация: 19.01.2012 Сообщений: 62 |
|
1 |
|
25.06.2012, 17:24. Показов 9336. Ответов 8
Создаю QMessageBox с 2 кнопками. При помощи setInformativeText вывожу сообщение. Оно располагается в 2 строках, а я хочу в 1 строку. Для этого надо увеличить длину окна с сообщением, но команды по изменению размеров просто игнорируются. setGeometry меняет только точку вывода, но не размер.
__________________
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
25.06.2012, 17:24 |
8 |
Прогер 632 / 263 / 15 Регистрация: 17.11.2010 Сообщений: 1,371 Записей в блоге: 2 |
|
25.06.2012, 18:11 |
2 |
Enforcer,
0 |
2732 / 1428 / 89 Регистрация: 08.09.2011 Сообщений: 3,746 Записей в блоге: 1 |
|
25.06.2012, 20:21 |
3 |
попробуйте перед тем как показать сообщение выставить setMinimumSize
0 |
Enforcer 9 / 9 / 1 Регистрация: 19.01.2012 Сообщений: 62 |
||||
26.06.2012, 17:41 [ТС] |
4 |
|||
Не помогает. Даже если убрать текст вообще. Добавлено через 1 час 35 минут
0 |
KeyGen 387 / 294 / 21 Регистрация: 07.08.2011 Сообщений: 790 Записей в блоге: 1 |
||||
29.11.2012, 01:29 |
5 |
|||
Разбирался с этим нашел такое решение:
Это установка по центру. Вопрос был о другом. Установить размер так и не смог.
0 |
Enforcer 9 / 9 / 1 Регистрация: 19.01.2012 Сообщений: 62 |
||||
16.10.2013, 17:20 [ТС] |
6 |
|||
setMinimumSize помогает если вместо exec использовать show.
В остальном добиться изменения размера так и не удалось. Кто-нибудь нашел решение задачи ? Добавлено через 48 минут
0 |
Диссидент 27211 / 16964 / 3749 Регистрация: 24.12.2010 Сообщений: 38,152 |
|
16.10.2013, 18:19 |
7 |
Enforcer, а если его унаследовать и перекрыть метод setMinimumSize?
0 |
9 / 9 / 1 Регистрация: 19.01.2012 Сообщений: 62 |
|
17.10.2013, 11:34 [ТС] |
8 |
Не пробовал.
0 |
4 ответа
Вы можете отредактировать css метки:
msg.setStyleSheet("QLabel{min-width: 700px;}");
Вы также можете отредактировать css кнопок для добавления поля или увеличения размера.
Например:
msg.setStyleSheet("QLabel{min-width:500 px; font-size: 24px;} QPushButton{ width:250px; font-size: 18px; }");
Существует также трюк:
QSpacerItem* horizontalSpacer = new QSpacerItem(800, 0, QSizePolicy::Minimum, QSizePolicy::Expanding);
QGridLayout* layout = (QGridLayout*)msg.layout();
layout->addItem(horizontalSpacer, layout->rowCount(), 0, 1, layout->columnCount());
Но это не работает для всех.
coyotte508
07 июнь 2016, в 02:52
Поделиться
Ответ coyotte508 привел к тому, что моя раскладка была ужасно смещена от центра и при разной ширине была обрезана. В поисках вокруг я нашел эту ветку, которая объясняет лучшее решение.
По сути, макет окна сообщения является сеткой, поэтому вы можете добавить к нему SpacerItem, чтобы контролировать ширину. Вот пример кода c++ по этой ссылке:
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();
Spencer
27 май 2018, в 07:43
Поделиться
Я хотел, чтобы ширина моего QMessageBox адаптировалась пропорционально длине текстового содержимого с определенным количеством буфера, чтобы избежать переноса строк. Изучив многочисленные форумы и темы, в том числе и этот, я придумал:
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());
Настройте жесткие числа в x_offset, y_offset и horizontalSpacer в соответствии с вашей ситуацией. Я надеялся, что это будет легче, чем это, но по крайней мере это работает.
Dave Sieving
26 апр. 2019, в 03:19
Поделиться
Вы можете QMessageBox
подкласс QMessageBox
и переопределить обработчик события изменения размера следующим образом:
void MyMessageBox::resizeEvent(QResizeEvent *Event)
{
QMessageBox::resizeEvent(Event);
this->setFixedWidth(myFixedWidth);
this->setFixedHeight(myFixedHeight);
}
ephemerr
05 март 2019, в 07:38
Поделиться
Ещё вопросы
- 1Protobuf-Net всегда десериализует пустой список
- 0Как создать новый экземпляр в Angularjs? Метод сохранения CRUD не работает
- 0jQuery validate плагин — только успешно показывать изображение «галочка», иначе при ошибке показывать «крестик» изображение
- 0Как получить доступ к `$ scope.search.value`?
- 0Метод удаления C ++ AVLtree
- 1Случайные числа меняются при изменении ориентации
- 0Phonegap и JqueryMobile блокируют события и функции пользовательского интерфейса
- 1Сообщение SignalR не работает при отправке со стороны сервера клиенту
- 0Заставить браузер открывать новые окна в стиле SW_HIDE?
- 0Angularjs $ интервал: использование функции обратного вызова в качестве параметра для передачи в функцию
- 0Загрузка CSS в представлениях в codeigniter ошибка
- 0Заполните выпадающий список из другой таблицы MySQL — php
- 1Заменить подстроку внутри строки новым GUID для каждой найденной подстроки
- 1Не удается сохранить дату календаря в базе данных в Java
- 1ClassCastException из редактора макетов в Eclipse ADT Plugin
- 1Общий способ перезаписи одного типа поля в типе объекта потока
- 0MySql Начальная и конечная цена (мин., Макс.) С внутренними соединениями
- 0Звонить по ссылке в CSS?
- 0блокировка матрицы дает ошибку сегментации
- 0Проверка наличия элемента в стеке
- 0В пользовательской директиве, какая функциональность у `controller` над` link`?
- 0Используйте мою переменную php в качестве формулы для вычисления чего-либо
- 1Как вы используете безголовый Chrome и прокси, используя селен в Python?
- 0Какая из этих таблиц лучше всего подходит для производительности (столбцы и строки)?
- 0Настроить таблицу MySQL для заказа по уникальному индексу
- 0AscW эквивалент из VB в C ++
- 0Как отключить кнопку на Angular
- 1npgsql 2.1.3 и EF 6: не удалось определить версию хранилища; требуется действительное подключение к хранилищу или указание версии
- 1Добавление WCF веб-сервиса Xamarin Studio
- 1Невозможно использовать ресурсы в производственном режиме с Tomcat
- 0Переверните строку, используя C и встроенную сборку
- 0Встроенные видео не отображаются
- 0META-теги перенаправляются при обнаружении браузера Chrome
- 0Возврат невременного объекта из функции C ++ с ограниченным сроком службы
- 0Спрайт не работает (фон не корректируется, а ссылка не существует?)
- 0Код jQuery для адаптации заполнения класса CSS
- 0php mysql — вставить один запрос из цикла while
- 1Проверка на стороне клиента RequiredFieldValidator для дочернего элемента составного элемента управления
- 1c # winforms -Pass параметр между модальными формами
- 0Ошибка Loopback 401 при попытке обновления
- 0Как получить правильную ссылку cms (с красивым url) от smarty в prestashop?
- 0если условие внутри программы не работает
- 1Текстовое поле теряет значение после обратной передачи (ASP — C #)
- 0Умный способ перетащить HTML структуру
- 1Динамическая загрузка Java-класса против реализации LUA
- 0Как удалить элемент и его дочерние элементы, используя класс php HTMLDOMDocument
- 0Клонирование элементов формы при клике дублирует данные
- 0mysql sql statment перестает разбирать один ряд
- 1Связь между операциями nio OP_READ и OP_WRITE
- 0MYSQL case case не работает с простым оператором
В настоящее время я работаю над локализацией приложения. Все переводит, как я ожидал, однако, 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();
Это дает мне это:
Следует отметить, что если слишком много увеличить отступ, он начнет покрывать текст — что я на самом деле не понимаю — но 3px кажется хорошим.
ОБНОВЛЕНИЕ 2:
После игры с этим, я думаю, QMessageBox
имеет фиксированную ширину, которая связана с самим текстом окна сообщения и не может быть изменена. Размер кнопок изменяется и соответствует тексту кнопки, если текст окна сообщения достаточно длинный, поэтому кажется, что размер кнопки не имеет никакого отношения к тому, что сам текст кнопки.
Я попытался настроить с setMinimumWidth
а также setFixedWidth
и коробка просто не меняет размер. На основе комментариев в этой ошибке QTBUG-7851, Я думаю QMessageBox
не может быть изменен программно. Было бы здорово, если бы кто-нибудь знал реальное решение этого вопроса, которое не включает создание собственного диалога.
ОБНОВЛЕНИЕ 3:
Основываясь на комментариях cbuchart, я понял, что существует таблица стилей .qss с min-width
установка вызывает QPushButton
Размеры не должны быть изменены должным образом.
2
Решение
Нет необходимости использовать таблицы стилей, хотя вам все равно придется создавать объект вручную вместо использования QMessageBox::question
,
Вы можете изменить макет окна сообщения для автоматического расширения, используя QLayout::setSizeConstraint
. Это заставит диалог изменить размер и подогнать его содержимое.
Пример (его также можно найти Вот):
#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;
}
2
Другие решения
Других решений пока нет …
- Forum
- Qt
- Newbie
- change text size and window size — qmessagebox
Thread: change text size and window size — qmessagebox
-
change text size and window size — qmessagebox
hi
i want to change text size and window size of qmessagebox,it is very small :
small_Qmessagebox.JPG
i want change to :
small_Qmessagebox2.jpg
tnx
-
Re: change text size and window size — qmessagebox
You can change the text size using html. For that :-
msgBox->setText("<font size="5">" + string + </font>);
To copy to clipboard, switch view to plain text mode
And for the size of messagebox
msgBox->setFixedSize(width,height);
To copy to clipboard, switch view to plain text mode
Heavy Metal Rules. For those about to rock, we salute you.
HIT THANKS IF I HELPED.
-
The following user says thank you to sonulohani for this useful post:
smemamian (3rd July 2013)
-
Re: change text size and window size — qmessagebox
Thank you for your reply.
1- it is correct :msgBox->setText("<font size=5>" + string + "</font>");
To copy to clipboard, switch view to plain text mode
2- messagebox does not change !
StringClass strclass;
strclass.getStringOne() + "</font>" ,QMessageBox::NoIcon,
QPixmap exportSuccess(":/PIC/award.png");
mb.setIconPixmap(exportSuccess);
mb.setFixedSize(100,100);
mb.exec()
To copy to clipboard, switch view to plain text mode
-
Re: change text size and window size — qmessagebox
Check with this:-
msg.setIconPixmap(QPixmap(":/error.svg"));
msg.setText("No images loaded");
msg.setInformativeText("There are no images in the list. Please create or load a project");
layout->addItem(horizontalSpacer, layout->rowCount(), 0, 1, layout->columnCount());
msg.exec();
To copy to clipboard, switch view to plain text mode
Heavy Metal Rules. For those about to rock, we salute you.
HIT THANKS IF I HELPED.
-
The following user says thank you to sonulohani for this useful post:
smemamian (4th July 2013)
Similar Threads
-
Replies: 2
Last Post: 13th December 2012, 14:56
-
Replies: 1
Last Post: 18th October 2011, 12:02
-
Replies: 0
Last Post: 13th January 2011, 17:52
-
Replies: 2
Last Post: 30th November 2007, 16:00
-
Replies: 3
Last Post: 31st October 2007, 09:16
Bookmarks
Bookmarks

Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
- BB code is On
- Smilies are On
- [IMG] code is On
- [VIDEO] code is On
- HTML code is Off
Forum Rules
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.