1,简介
Qt 自带的 Tree、Table控件在点击空白处时无法取消选中,
有时候需要这种功能,只好自己DIY
2,效果
3,主要代码
继承QTreeView 写了个MyTreeView,在UI设计器内提升。
MyTreeView.h:
#ifndef MYTREEVIEW_H
#define MYTREEVIEW_H
#include <QTreeView>
#include <QMouseEvent>
//改造QTreeView,实现点击空白处时取消选择
class MyTreeView : public QTreeView
{
Q_OBJECT
public:
MyTreeView(QWidget *parent = Q_NULLPTR);
signals:
void sigPressEmpty();
protected:
void mousePressEvent ( QMouseEvent * event ) ;
};
#endif
MyTreeView.cpp:
#include "MyTreeView.h"
MyTreeView::MyTreeView(QWidget *parent)
: QTreeView(parent)
{
}
void MyTreeView::mousePressEvent(QMouseEvent *event)
{
QPoint p = event->pos();
QModelIndex index = indexAt(p);
if(!index.isValid())
{
setCurrentIndex(QModelIndex()); //实现点空白处取消选择
emit sigPressEmpty();
return;
}
QTreeView::mousePressEvent(event);
}
4,演示Demo源码下载
本专栏配套源码,可在Qt学习群免费下载:
群号码:1149411109
群名称:Qt实战派学习群