繁体   English   中英

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将显示为尽可能大,因此可能的请求是使用sizeHint()QDialog的大小更改为建议的QLabel大小:

#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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM