在窗体上鼠标事件无法实时获取鼠标是否在Qcombox的区域上,继承Qcombox使用事件过滤器解决该问题
class NewComboBox;
class myFrame: public QDialog
{
Q_OBJECT
public:
myFrame(QWidget* parent=null);
~myFrame(){};
protected:
void mouseMoveEvent(QMouseEvent *event);
private:
NewComboBox *m_pComboBox
};
myFrame::myFrame(QWidget* parent):QDialog(parent)
{
QHBoxLayout* pLayOut = new QHBoxLayout;
pLayOut->setContentsMargins(16, 10, 16, 10); //设置布局左右顶底距离的位置
m_pCombox = new NewComboBox(this);
this->setLayout(pLayOut); //将布局加入到窗体
}
void myFrame::mouseMoveEvent(QMouseEvent *event)
{
QPoint curr = QCursor::pos(); //鼠标位置
if (m_pComboBox&&
m_pComboBox->geometry().contains(this->mapFromGlobal(curr))) //转为全局坐标,窗体时鼠标移动事件这种方式无法//根据鼠标的移动试试获取鼠标的位置是否在Qcombox上
{
int nLenght = m_pComboBox->width();
QString strText = m_pComboBox->lineEdit()->placeholderText();
QFontMetrics fmOther = m_pComboBox->fontMetrics();
int nTextLength = fmOther.width(strCurText); //获取文字长度
if (nTextLength > nLenght)
{
QToolTip::showText(curr, strCurText); //提示信息
}
}
QDialog::mouseMoveEvent(event);
}
class NewComboBox :public QComboBox
{
public:
NewComboBox(QWidget *pParent = nullptr);
~NewComboBox();
protected:
bool eventFilter(QObject *pTarget, QEvent * pEvt);
};
bool NewComboBox::eventFilter(QObject *pTarget, QEvent * pEvt)
{
//事件过滤,鼠标移动类型,鼠标进入
if (pEvt->type() == QEvent::MouseMove || pEvt->type() == QEvent::HoverEnter || pEvt->type() == QEvent::HoverMove)
{
QPoint curr = QCursor::pos();
int nLenght = this->width();
QString strText = this->lineEdit()->placeholderText();
QFontMetrics fmOther = this->fontMetrics();
int nTextLength = fmOther.width(strCurText);
if (nTextLength > nActualLenght)
{
QToolTip::showText(curr, strText); //提示信息
}
}
return QComboBox::eventFilter(pTarget, pEvt);
}