2017-07-19 78 views
-1

我想分配父變量(在子類的構造函數),然後我想使它成爲子類的成員變量。我怎麼能在Qt中做到這一點?Qt:如何將父項設置爲其子類的成員變量?

代碼:

PopupServer::PopupServer(QWidget *parent) { 
//I need to store the parent in variable Win 
//and make it member variable of PopupServer class 

} 

void PopupServer::showPopup(const QString &text,const int &tim) { 
    QLabel qPopup= new QLabel; qPopup.setText(text); 
    qPopup.setFrameStyle(QLabel::Raised | QLabel::Panel); 
    qPopup.setAlignment(Qt::AlignCenter); 
    qPopup.setFixedSize(200,100); 
    int width; 
    int height; 
    width= win.width(); 
    height= win.height(); 
    qPopup.move(width-qPopup.width(),height-qPopup.height()); 
    qPopup.show(); 
} 
+0

顯示您的代碼。 – eyllanesc

+0

PopupServer :: PopupServer(QWidget的*父) {// 我需要父存儲在變量贏,並使其PopupServer 類的成員變量} 無效PopupServer :: showPopup(常量QString的&文本,const int的&TIM) QLabel qPopup = new QLabel; qPopup.setText(text); qPopup.setFrameStyle(QLabel :: Raised | QLabel :: Panel); qPopup.setAlignment(Qt :: AlignCenter); qPopup.setFixedSize(200,100); int width; int height; width = win.width(); height = win.height(); qPopup.move(width-qPopup.width(),height-qPopup.height()); qPopup.show(); } – Vector

+0

你想在課堂的任何地方訪問父母嗎? – eyllanesc

回答

1

是繼承自QObject可以通過parent()方法訪問父,而在你的情況你的類從QWidget的繼承和QWidget的從QObject的繼承,那麼你的類也有所有課程方法。所以你不需要創建一個屬性。

按照documentation

的QObject *的QObject ::父()const的

將指針返回到父對象。

你的情況:

void PopupServer::showPopup(const QString &text,const int &tim) { 
    QLabel qPopup= new QLabel; qPopup.setText(text); 
    qPopup.setFrameStyle(QLabel::Raised | QLabel::Panel); 

    Popup.setAlignment(Qt::AlignCenter); 
    qPopup.setFixedSize(200,100); 

    int width; int height; 

    QWidget * win = qobject_cast<QWidget *>(parent()); 
    if(win){ 
     width= win->width(); 
     height= win->height(); 
     qPopup.move(width-qPopup.width(),height-qPopup.height()); 
    } 

    qPopup.show(); 

} 
+0

感謝您的幫助:)我嘗試了另一種方法。它的工作 – Vector

0

爲了使父(主窗口)子類(彈出式服務器)的成員變量,添加:

在popupserver.h:

private: 
    QWidget *win; 

在popupserverserver.cpp中,(構造函數):

PopupServer::PopupServer(QWidget *parent) 
{ 
win=parent; } 
相關問題