c++ - 如何让图形保持在主窗口的中央

标签 c++ qt qt5 qwidget

我正在学习 Qt5 并使用 Qt 5.9.1。现在我遇到一个问题:如何在主窗口大小发生变化的情况下,让图形保持在主窗口的中央?

去年我在类里面学习了MFC,老师告诉我们,为了让图形始终停留在窗口中,我们应该这样做:

  1. 让视口(viewport)的原点成为客户区的中心;
  2. 让视口(viewport)的大小为客户区的大小;
  3. 以窗口原点为图形外接矩形的中心;
  4. 设窗口大小为图形外接矩形的大小。

所以我在 Qt5 中做了同样的事情:

// main.cpp
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QtGuiApplication1 w;
    // get the size and center of client area
    // and then pass the values to QtGuiApplication
    int width = QApplication::desktop()->availableGeometry().width();
    int height = QApplication::desktop()->availableGeometry().height();
    QPoint center = QApplication::desktop()->availableGeometry().center();
    w.setViewport(center,width,height);

    w.show();
    return a.exec();
}

// GtGuiApplication.cpp 
void QtGuiApplication1::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    // set the viewport
    painter.setViewport(centerOfViewport.x(),centerOfViewport.y(), widthOfViewport, heightOfViewport);

    static const QPointF points[4] = {
    QPointF(10.0, 10.0),
    QPointF(10.0, 80.0),
    QPointF(50.0, 80.0),
    QPointF(10.0, 10.0)
    };

    // set the window
    painter.setWindow(30,45,40,70);

    painter.drawPolyline(points, 4);
}

然而,所有这些都不起作用。在我设置视口(viewport)和窗口之前:

enter image description here

在我完成设置之后:

enter image description here

最佳答案

我不明白你在行中指出的是什么,也许它在MFC中实现了,但是不分析它们就不能接受规则,你必须理解它们并且似乎你没有正确理解它们就想应用它们。

根据您指出的内容,您希望多边形始终在窗口内居中,并且在您的代码中您使用的窗口大小没有意义,因为窗口可以位于屏幕上的任何位置,从那里开始我们走得很糟糕。

如果你想让多边形的中心成为窗口的中心,那么你必须计算两个点,第一个引用源是与多边形接壤的矩形的顶峰,第二个是窗口的矩形,如果我们减去两个位置,我们得到画家必须移动的东西,使两个点重合。

void QtGuiApplication1::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    static const QVector<QPointF> points = {
        QPointF(10.0, 10.0),
        QPointF(10.0, 80.0),
        QPointF(50.0, 80.0),
        QPointF(10.0, 10.0)
    };
    QPainterPath path;
    path.addPolygon(QPolygonF(points));
    QPointF center_path = path.boundingRect().center();
    painter.translate(rect().center()-center_path);
    painter.drawPath(path);
}

enter image description here

enter image description here

关于c++ - 如何让图形保持在主窗口的中央,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52551325/

相关文章:

c++ - QDataStream成员间分配

c++ - 如何在具有XY轴Qt的图形上绘制矩形

c++ - C++中的虚拟变量?

Qt |无法让任何加密库工作

qt - 如何使 wkhtmltopdf 在 Debian 9 "Stretch"上的 Odoo v10 中工作?

当使用 vector 作为键时,C++ unordered_map 失败

c++ - 我在玩VS2017的时候发现了一些东西

c++ - 为 C/C++ 中的项目的 makefile 生成依赖项

c++ - QLineWidget returnPressed 信号不工作

c++ - 是否可以连接到 QApplication 通知信号?