c++ - Qt:如何将parent设置为其子类的成员变量?

标签 c++ qt qt5

我试图将父变量分配给一个变量(在子类的构造函数中),然后我想让它成为子类的成员变量。我如何在 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(); 
} 

最佳答案

所有继承自QObject的类都可以通过parent()方法访问父类,在你的例子中你的类继承自QWidget,而QWidget继承自QObject,所以你的类也有那个方法.因此您不需要创建属性。

根据documentation :

QObject *QObject::parent() const

Returns a pointer to the parent object.

在你的情况下:

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

} 

关于c++ - Qt:如何将parent设置为其子类的成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45181576/

相关文章:

c++ - 如何解决内存碎片

qt - 如何按升序对 ListView 项目进行排序?

css - 我怎样才能在我的 Qt 应用程序中简单地解析一个 CSS 类 (!) 文件?

c++ - QTableView row setEnabled 等效函数调用?

python - centralWidget 大小似乎错误?

c++ - 使用 QT 在 KDE5 中进行窗口和装饰样式编程

c++ - 使用 __m64 引用将 C++ 项目转换为 x64

c++ - 我们真的需要 C++11 中的 "enum class"吗?

c++ - Linux/C++ : getting user's directory without leaks

c++ - 在实时数据流上检测峰值