QDialog基于QLabel内容进行扩展

问题描述 投票:0回答:1

我想显示然后在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。

c++ qt qt5 qlabel qdialog
1个回答
1
投票

由于你没有使用过QLayoutQLabel会尽可能大地显示,可能的要求是将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();
}
© www.soinside.com 2019 - 2024. All rights reserved.