2017-07-19 1 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 {私は変数勝利に親を保存し、それをPopupServerクラス のメンバ変数を作成する必要があり //} PopupServer(QWidgetの*親) :: showPopup(のconst QStringの&テキスト、のconst int型&ティム) { QLabel qPopup =新しいQLabel; qPopup.setText(text); qPopup.setFrameStyle(QLabel :: Raised | QLabel :: Panel); qPopup.setAlignment(Qt :: AlignCenter); qPopup.setFixedSize(200,100); int幅; int高さ; width = win.width(); height = win.height(); qPopup.move(width-qPopup.width()、height-qPopup.height()); qPopup.show(); } – Vector

+0

クラスのどこにでも親にアクセスしますか? – eyllanesc

答えて

1

parent()方法を介して親にアクセスすることができますQObjectを継承し、かつので、あなたのクラスにもいることを持って、あなたのケースでは、あなたのクラスはQWidgetから継承し、QWidgetのはQObjectをから継承したすべてのクラス方法。したがって、属性を作成する必要はありません。親オブジェクトへのポインタを返します

QObjectを*はQObject ::親()constは

documentationによると

。あなたのケースでは

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; 

popupserver.cpp(コンストラクタ):

PopupServer::PopupServer(QWidget *parent) 
{ 
win=parent; } 
関連する問題