QDialog 基于 QLabel 内容扩展

QDialog expanding base on the QLabel content

我想显示并在 5 秒后关闭对话框。对话框需要根据标签的内容自动调整大小(水平和垂直)。这是我的代码:

#include <QApplication>
#include <QDialog>
#include <QLabel>
#include <QTimer>

void notify (int intTime=1000)
{
    QDialog notify;
    notify.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    notify.setWindowFlag(Qt::FramelessWindowHint);
    QLabel *lbl = new QLabel(&notify);
    lbl->setText("This is a test This is a test This is a test This is a test This is a test This is a test This is a test");
    QApplication::processEvents();
    notify.adjustSize();
    QTimer::singleShot(intTime, &notify, SLOT(close()));
    notify.exec();
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    notify(5000);
    exit(0);
//  return a.exec();
}

它不会根据标签大小展开对话框。外观如下:

我该如何解决? (如果有更好的方法,也请告诉我。)

我在 Linux 中使用 Qt5。

由于您没有使用 QLayout,因此 QLabel 将尽可能大地显示,可能的请求是将 QDialog 的大小更改为建议的大小QLabelsizeHint():

#include <QApplication>
#include <QDialog>
#include <QLabel>
#include <QTimer>

void notify (int intTime=1000)
{
    QDialog notify;
    notify.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    notify.setWindowFlag(Qt::FramelessWindowHint);
    QLabel *lbl = new QLabel(&notify);
    lbl->setText("This is a test This is a test This is a test This is a test This is a test This is a test This is a test");
    QApplication::processEvents();
    notify.resize(lbl->sizeHint());
    QTimer::singleShot(intTime, &notify, SLOT(close()));
    notify.exec();
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    notify(5000);
    exit(0);
//  return a.exec();
}

另一种可能的解决方案是使用 QLayout:

#include <QApplication>
#include <QDialog>
#include <QLabel>
#include <QTimer>
#include <QVBoxLayout>

void notify (int intTime=1000)
{
    QDialog notify;
    QVBoxLayout *lay = new QVBoxLayout(&notify);
    //notify.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    notify.setWindowFlag(Qt::FramelessWindowHint);
    QLabel *lbl = new QLabel;
    lay->addWidget(lbl);
    lbl->setText("This is a test This is a test This is a test This is a test This is a test This is a test This is a test");
    QApplication::processEvents();
    QTimer::singleShot(intTime, &notify, SLOT(close()));
    notify.exec();
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    notify(5000);
    exit(0);
//  return a.exec();
}