1.解决方案
// 直接添加的话 应该自动创建了一个QToolButton
// 但是没有办法获取这个QToolButton 无从设置事件过滤 QTooltip的样式等
QAction* cs = new QAction("哈哈",this);
toolbar->addAction(cs);
// 正确的方法
toolbar = new QToolBar(this);
QAction* cs = new QAction("哈哈",this);
//toolbar->addAction(cs); // 直接添加无法控制QToolButton
//添加QToolButton
QToolButton* qtbtn = new QToolButton(this);
qtbtn->setDefaultAction(cs); // QAction
//qtbtn->setToolTipDuration(1); // 可以控制显示持续事件 1ms看不到
qtbtn->installEventFilter(this); // 添加事件过滤
//qtbtn->setStyleSheet("QToolTip{ // 设置QToolTip样式
toolbar->addWidget(qtbtn); // 不用addAction
2.调试过程
2.1 主函数中代码,重写QApplication的notify
// 重写notify函数 输出相关事件
class MyApplication : public QApplication
{
public:
MyApplication(int argc, char *argv[]) :QApplication(argc, argv){}
virtual bool notify(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::ToolTip)
{
//qDebug() <<"classname:"<<obj->metaObject()->className();
if(obj->metaObject()->className() == QStringLiteral("QToolButton"))
{
qDebug() <<"objectname:"<<obj->objectName();
//qDebug() <<"parent_classname:"<<obj->parent()->metaObject()->className();
qDebug() <<"parent_objectname:"<<obj->parent()->objectName();
//qDebug() <<"p_p_objectname:"<<obj->parent()->parent()->objectName();
}
}
return QApplication::notify(obj,event);
}
};
int main(int argc, char* argv[])
{
// 这里调用MyApplication
MyApplication a(argc, argv);
2.2 在窗体中添加事件过滤,打印相关事件
bool MyWidget::eventFilter(QObject *obj, QEvent *event)
{
//return true;
//qDebug()<<obj->metaObject()->className()<<":"<<event->type();
//if (obj->metaObject()->className() == QStringLiteral("QToolButton"))
//{
//qDebug()<<obj->metaObject()->className()<<":"<<event->type();
//return true;
//}
if (event->type() == QEvent::ToolTip)
{
qDebug()<<obj->metaObject()->className()<<":"<<event->type();
return true;
}
//qDebug()<<obj->metaObject()->className()<<":"<<event->type();
return QWidget::eventFilter(obj, event);
}
2.3 测试代码 不带QToolButton
toolbar = new QToolBar(this);
toolbar->setObjectName("cs_toolbar");
QAction* cs = new QAction("哈哈",this);
cs->setToolTip("1");
cs->setObjectName("cs_qaction");
cs->installEventFilter(this); //增加过滤器 打印只有QAction : QEvent::ActionChanged
toolbar->installEventFilter(this);
toolbar->addAction(cs);
// 打印
objectname: "" // 创建了一个QToolButton 没有objectname
parent_objectname: "cs_toolbar" // 确实隶属 cs_toolbar
2.4 测试代码 带QToolButton
// 测试
toolbar = new QToolBar(this);
toolbar->setObjectName("cs_toolbar");
QAction* cs = new QAction("哈哈",this);
cs->setToolTip("1");
cs->setObjectName("cs_qaction");
cs->installEventFilter(this); //增加过滤器 打印只有QAction : QEvent::ActionChanged
toolbar->installEventFilter(this);
//toolbar->addAction(cs);
// 添加QToolButton
QToolButton* qtbtn = new QToolButton(this);
qtbtn->setObjectName("cs_qtoolbutton");
qtbtn->setDefaultAction(cs);
qtbtn->setToolTip("22");
//qtbtn->setToolTipDuration(1);
qtbtn->installEventFilter(this);
toolbar->addWidget(qtbtn);
// 打印
objectname: "cs_qtoolbutton"
parent_objectname: "cs_toolbar"
QToolButton : QEvent::ToolTip