2017-03-15 60 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

美妙的,這工作!謝謝老闆 ;) –