在主界面重写mousePressEvent函数,代码如下
void mainwdg::mousePressEvent(QMouseEvent* event)
{
//是否时左键
if (event->button() == Qt::LeftButton)
{
//获取鼠标坐标
int mouse_x = QCursor::pos().x();
int mouse_y = QCursor::pos().y();
//获取鼠标点击到的控件
QWidget* subWidget = QApplication::widgetAt(mouse_x, mouse_y);
QString helpstr = subWidget->toolTip();
if (!helpstr.isEmpty())
{
QLabel* label = dynamic_cast<QLabel*>(subWidget);//只有QLabel设置了toolTip
helpstr = label->text() + " : " + helpstr;
m_ui->textBrowser->setText(helpstr);
}
/*
//我的代码里只有QLabel设置了toolTip,所以dynamic_cast转化为QLabel时有效的
QLabel* label = dynamic_cast<QLabel*>(subWidget);
//QLineEdit 的转化是不成功的,lineEdit此时为NULL
//所以也可以根据 指针是否有效来判断控件属于哪个类型
QLineEdit *lineEdit= dynamic_cast<QLineEdit*>(subWidget);*/
}
return QDialog::mousePressEvent(event);
}