QDialog根据QLabel内容进行扩展

时间:2018-03-05 21:00:38

标签: c++ qt qt5 qlabel qdialog

我想显示然后在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();
}

它不会根据标签大小扩展对话框。以下是它的外观:

enter image description here

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

我在Linux中使用Qt5。

1 个答案:

答案 0 :(得分:1)

由于您未使用QLayoutQLabel将尽可能大地显示,可能的请求是将QDialog的大小更改为建议的{{1}大小1}}与QLabel

sizeHint()

另一种可能的解决方案是使用#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