增加 QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);对鼠标类型进行强制转换,转化为鼠标事件,拿到鼠标事件指针映射到对应的按键,成功实现.单击就能有反应.
bool Dialog::eventFilter(QObject *watched, QEvent *event)
{
if(watched==ui->textEdit)//监视到了ui->labSC
{
if(event->type()==QEvent::Enter){
ui->textEdit->setStyleSheet("background-color:rgb(170,255,255);");
}
else if(event->type()==QEvent::Leave)
{
// ui->textEdit->setText("单击我");
ui->textEdit->setStyleSheet("");
}
else if(event->type()==QEvent::MouseButtonPress){//鼠标键按下右键可以
ui->textEdit->setText("button pressed");//按压
}
else if(event->type()==QEvent::MouseButtonRelease){//鼠标键释放
// ui->textEdit->setText("button released");//释放
}
}
if(watched==ui->textEdit_2)
{
QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
if(event->type()==QEvent::Enter){
ui->textEdit_2->setStyleSheet("background-color:rgb(85,255,127);");
}
else if(event->type()==QEvent::Leave)
{
ui->textEdit_2->setText("双击我");
ui->textEdit_2->setStyleSheet("");
}
else if(mouseEvent->button()== Qt::LeftButton){//鼠标双击捕捉不到单击双击事件
qDebug()<<"test";
ui->textEdit_2->setText("danji ");
}
}
return QWidget::eventFilter(watched,event);
}
但是有个弊端,因为textedit的光标因为一直在里面闪烁,所以捕捉不灵敏,只能是移开让光标在别处,然后再回来单击,就可以实现.