简体   繁体   中英

Qt:How to set the parent as the member variable of its child class?

I am trying to assign the parent to a variable (at the constructor of the child class )and then I want to make it the member variable of the child class. how can I do that in Qt ?

Code:

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(); 
} 

All classes that inherit from QObject can access the parent through the parent() method, and in your case your class inherits from QWidget, and QWidget inherits from QObject, so your class also has that method. So you do not need to create an attribute.

According to the documentation :

QObject *QObject::parent() const

Returns a pointer to the parent object.

In your case:

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(); 

} 

To make the parent(Main window) member variable of child class(Popup Server),add:

In popupserver.h :

private:
   QWidget *win;

In popupserver.cpp,( the constructor ):

PopupServer::PopupServer(QWidget *parent)
{
win=parent; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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