2017-03-15 61 views
1

我的Qt应用程序由在QStackedLayout()上添加的几个屏幕组成。现在经过一些使用后,我想要一个确认动作的小弹出窗口,并在几秒钟后消失。我想要的是带有黑色边框和一些文字的灰色矩形。没有按钮,没有标题栏。如何在Qt中编写自定义弹出窗口?

我试着用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中?

+0

***此外,大小不能调整***我知道这是错误的,因为在我目前的应用程序之一,我设置消息框的宽度来显示一条长消息。我将不得不在稍后检查我的实施。 – drescherjm

回答

3

首先,我想推荐Qt文档的Windows Flags Example。它提供了一个很好的示例来玩这个话题。在此示例中,导出了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编译。下图显示了一个snaphot:

Snapshot of testQPopup.exe

为了使弹出更好的可见的(因为我喜欢它),我改变了QLabel对弹出窗口的背景色。而且,我忍不住要添加一点倒计时。

+0

美妙的,这工作!谢谢老板 ;) –