我的 Qt 应用程序由添加在QStackedLayout(). 现在在一些用户操作之后,我想要一个小弹出窗口来确认操作并在几秒钟后消失。我想要的是一个带有黑色边框和一些文本的灰色矩形。没有按钮,没有标题栏。
我尝试使用 QMessage Box(请参阅下面的代码)来执行此操作,但通常似乎无法调整QMessageBox(). 也不能调整大小。
QMessageBox* tempbox = new QMessageBox;
tempbox->setWindowFlags(Qt::FramelessWindowHint); //removes titlebar
tempbox->setStandardButtons(0); //removes button
tempbox->setText("Some text");
tempbox->setFixedSize(800,300); //has no effect
tempbox->show();
QTimer::singleShot(2000, tempbox, SLOT(close())); //closes box after 2 seconds
Run Code Online (Sandbox Code Playgroud)
那么,如何在 Qt 中编写自定义弹出窗口?
首先,我想推荐Qt 文档的Windows 标志示例。它提供了一个很好的示例来处理这个主题。在此示例中,QWidget导出 a 以显示不同标志的效果。这让我想到,QWidget如果Qt::WindowFlags设置了适当的,可能任何都可以用于此目的。我选择QLabel是因为
QFrame,因此可以有一个框架。源代码testQPopup.cc:
// standard C++ header:
#include <iostream>
#include <string>
// Qt header:
#include <QApplication>
#include <QLabel>
#include <QMainWindow>
#include <QTimer>
using namespace std;
int main(int argc, char **argv)
{
cout << QT_VERSION_STR << endl;
// main application
#undef qApp // undef macro qApp out of the way
QApplication qApp(argc, argv);
// setup GUI
QMainWindow qWin;
qWin.setFixedSize(640, 400);
qWin.show();
// setup popup
QLabel qPopup(QString::fromLatin1("Some text"),
&qWin,
Qt::SplashScreen | Qt::WindowStaysOnTopHint);
QPalette qPalette = qPopup.palette();
qPalette.setBrush(QPalette::Background, QColor(0xff, 0xe0, 0xc0));
qPopup.setPalette(qPalette);
qPopup.setFrameStyle(QLabel::Raised | QLabel::Panel);
qPopup.setAlignment(Qt::AlignCenter);
qPopup.setFixedSize(320, 200);
qPopup.show();
// setup timer
QTimer::singleShot(1000,
[&qPopup]() {
qPopup.setText(QString::fromLatin1("Closing in 3 s"));
});
QTimer::singleShot(2000,
[&qPopup]() {
qPopup.setText(QString::fromLatin1("Closing in 2 s"));
});
QTimer::singleShot(3000,
[&qPopup]() {
qPopup.setText(QString::fromLatin1("Closing in 1 s"));
});
QTimer::singleShot(4000, &qPopup, &QLabel::hide);
// run application
return qApp.exec();
}
Run Code Online (Sandbox Code Playgroud)
我在 Windows 10(64 位)上用 VS2013 和 Qt 5.6 编译。下图显示了快照:
为了使弹出窗口更好地可见(并且因为我喜欢它),我更改了QLabelfor 弹出窗口的背景颜色。而且,我忍不住要加一点倒计时。
| 归档时间: |
|
| 查看次数: |
4817 次 |
| 最近记录: |