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