繁体   English   中英

如何在Qt中编写自定义弹出窗口?

[英]How can I program a custom popup Window in Qt?

我的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

那么,如何在Qt中编写自定义弹出窗口?

首先,我想推荐Qt文档的Windows Flags示例 它提供了一个很好的样本来讨论这个主题。 在此示例中,派生了一个QWidget以显示不同标志的效果。 这让我想到如果设置了适当的Qt::WindowFlags ,可能会使用任何QWidget 我之所以选择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();
}

我在Windows 10(64位)上使用VS2013和Qt 5.6编译。 下图显示了一个快照:

testQPopup.exe的快照

为了让弹出窗口更好地可见(因为我喜欢它),我改变了弹出窗口的QLabel的背景颜色。 而且,我无法抗拒添加一点点倒计时。

暂无
暂无

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

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