当前位置:网站首页>Qt QWidget嵌套相对位置获取 (qt 画线 嵌套)
Qt QWidget嵌套相对位置获取 (qt 画线 嵌套)
2022-06-23 03:56:00 【超自然祈祷】
使用函数
QPoint QWidget::mapToGlobal(const QPoint &pos) const
.h文件
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
void paintEvent(QPaintEvent *);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
.cpp文件
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPainter>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::paintEvent(QPaintEvent *)
{
QPainter p(this);
p.setPen(Qt::blue);
p.drawLine(ui->pushButton->pos(),ui->pushButton_3->pos());
p.setPen(Qt::red);
p.drawLine(ui->pushButton->pos(),ui->pushButton_2->pos());
p.setPen(Qt::green);
p.drawLine(ui->pushButton->pos(), ui->pushButton_2->mapToGlobal( QPoint(0,0) - this->mapToGlobal( QPoint(0,0)) ));
}
.ui文件 和 运行结果 截图

按代码上的颜色分辨
pushButton_3、pushButton 是同级,都在界面上(蓝色线位置正确)
pushButton_2 是在一个widget里嵌套的 使用pushButton_2->pos()得到的是它在方框中的位置,所以连线位置出错(红色线)
而绿色线是使用mapToGlobal函数,窗口、pushButton_2都相对于显示器的位置,这样计算的位置就正确了。
边栏推荐
猜你喜欢
随机推荐
SwiftUI 2.0 课程笔记 Chapter 4
Zygote process
JDBC入门学习(三)之事务回滚功能的实现
TIOBE 编程语言排行榜是编程语言流行趋势的一个指标
Go 分组 & 排序
pkav简单爆破
I have been engaged in software testing for 5 years and have changed jobs for 3 times. I have understood the field of software testing
渗透测试基础 | 附带测试点、测试场景
Event日志关键字:EventLogTags.logtags
Servlet self study notes
Penetration test basis | attached test points and test scenarios
戏问花门酒家翁
开源生态|超实用开源License基础知识扫盲帖(下)
shutdown关机命令
【Leetcode】最长递增子序列问题及应用
How to conduct exploratory data analysis
Calculate Euclidean distance and cosine similarity
In unity, how to read and write a scriptableobject object in editor and runtime
JVM原理之内存模型
618如何冲出重围?海尔智家:做好用户的数字化









