Q:

Fit QDialog window to size of text

I have a QDialog class that takes in a QString. I am calling setFixedSize with a set width and height but I want the QDialog to be more dynamic and fit to the size of the text.
I have tried adjustSize() but all that did was shrink the window to the point where the text was cut off.
ConfirmDialog::ConfirmDialog(const QString& message, QWidget* parent)
: QDialog(parent)
{
    setFixedSize(WIDTH, HEIGHT);

    statusLabel->setText(tr("Confirmation"));
    statusDetailsLabel->setText(message);
    statusDetailsLabel->setWordWrap(true);
}

I always see a Window with size of dimensions WIDTH and HEIGHT. I want it to fit the test.

A:

One way would be to use Font Metrics to get the bounding rects of each label, and then set the window size to the sum of both rects + some padding to make it look nice.
One problem you will run into is having wordwrap on.  How do you determine the width of the window, if you are word wrapping?  So I've added a "MAXWIDTH" for the window.  If your text is shorter and does not require word wrap - the window will shrink to fit it.  If it does require word wrap, it will not go over your set size.
ConfirmDialog::ConfirmDialog(const QString& message, QWidget* parent)
: QDialog(parent)
{
    const int MAXWIDTH = 400;
    const int VERTICALPADDING = 50;

    // Create Layout
    QLabel *statusLabel = new QLabel(this);
    QLabel *statusDetailsLabel = new QLabel(this);
    QVBoxLayout *layout = new QVBoxLayout();
    layout->addWidget(statusLabel);
    layout->addWidget(statusDetailsLabel);
    setLayout(layout);

    // Populate Text
    statusLabel->setText(tr("Confirmation"));
    statusDetailsLabel->setText(message);
    statusDetailsLabel->setWordWrap(false); // Start w/ word wrap off.

    // Font metrics to get the sizes of our text.
    QFontMetrics fontMetricsLabel(statusLabel->font());
    QFontMetrics fontMetricsDetail(statusDetailsLabel->font());

    // Get max width - label or detail lable, whichever is longer.
    int width = std::max(fontMetricsLabel.boundingRect("Confirmation").width(),
                         fontMetricsDetail.boundingRect(message).width());

    // Check that we do not go over our MAXWIDTH.
    if(width > MAXWIDTH) width = MAXWIDTH;

    // Enable word wrapping.
    statusDetailsLabel->setWordWrap(true);

    // Get the heigts of both boxes.
    int height = std::max(fontMetricsLabel.boundingRect("Confirmation").height(),
                         fontMetricsDetail.boundingRect(message).height());

    // Set window size.
    this->setFixedSize(width, height + VERTICALPADDING);

}

