我想显示然后在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(¬ify);
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, ¬ify, 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
的大小改为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(¬ify);
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, ¬ify, 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(¬ify);
//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, ¬ify, SLOT(close()));
notify.exec();
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
notify(5000);
exit(0);
// return a.exec();
}