QT子窗口显示在父窗口中间(备忘)

方法一: 

/*this为主窗口指针 showPanel为子窗口指针*/
QPoint globalPos = this->mapToGlobal(QPoint(0,0));//父窗口绝对坐标
int x = globalPos.x() + (this->width() - showPanel->width()) / 2;//x坐标
int y = globalPos.y() + (this->height() - showPanel->height()) / 2;//y坐标
showPanel->move(x, y);//窗口移动 

方法二: 

QWidget *widget = nullptr;
//获取程序所有的widget
QWidgetList widgetList = QApplication::allWidgets();
//获取父窗口指针 此处获取objectName 可根据需求自行判断
for(int i=0; iobjectName() == "MainWindow"){
        widget = widgetList.at(i);
    }
}
if(widget){
 //获取父窗口geometry
    QRect rect = widget->geometry();
    //计算显示原点
    int x = rect.x() + rect.width()/2 - this->width() /2;
    int y = rect.y() + rect.height()/2 - this->height();
    this->move(x, y);
}

你可能感兴趣的:(qt,c++)