当它在QHeaderView部分之间的边界下时,如何防止变换光标到SplitHCursor

时间:2014-10-12 15:07:08

标签: qt qtablewidget qcursor

N列,左侧是手动调整大小的宽度。仅当具有手动调整大小的列正在调整大小时,其他列宽度才会调整大小。当光标位于部分的边框下而不需要手动调整大小时,我需要防止光标图标改变。

enter image description here

我尝试做什么。但这项工作并不是很好。

table_header_border.zip

#include "mainwindow.h"
#include "ui_mainwindow.h"

const int N = 2;

//==============================================================================

int nWidth(const QTableWidget *table)
{
    int ret = 0;

    if (table->verticalHeader()->isVisible())
    {
        ret += table->verticalHeader()->width();
    }

    for (int i = 0; i < N; i++)
    {
        ret += table->columnWidth(i);
    }

    return ret;
}

bool isInNColumns(const QTableWidget *table)
{
    QPoint cursorPos = table->mapFromGlobal(QCursor::pos());
    return cursorPos.x() < nWidth(table) + 5;
}

//==============================================================================

class MyHorizontalHeader : public QHeaderView
{
public:
    MyHorizontalHeader(QWidget *parent=0) : QHeaderView(Qt::Horizontal, parent)
    {
        setMouseTracking(true);
    }
private slots:
    void mouseMoveEvent(QMouseEvent *event)
    {
        QHeaderView::mouseMoveEvent(event);
        if (cursor().shape() == Qt::SplitHCursor)
        {
            QTableWidget *table = dynamic_cast<QTableWidget *>(parent());
            if (table != NULL && !isInNColumns(table))
            {
                qApp->setOverrideCursor(QCursor(Qt::ArrowCursor));
                return;
            }
            qApp->setOverrideCursor(QCursor(Qt::SplitHCursor));
        }
    }
};

//==============================================================================

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->tableWidget->setHorizontalHeader(new MyHorizontalHeader(this));
}

MainWindow::~MainWindow()
{
    delete ui;
}

2 个答案:

答案 0 :(得分:1)

您应该使用QEvent::EnterQEvent::Leave来获得更好的结果。

使用下一个事件过滤器:

在标题中:

protected:
     bool eventFilter(QObject *obj, QEvent *event);

在构造函数中:

qApp->installEventFilter(this);

EventFilter:

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{  
    if (obj == ui->tableWidget && event->type() == QEvent::Enter)
    {
        qApp->setOverrideCursor(QCursor(Qt::ArrowCursor));
        //or
        qApp->setOverrideCursor(ui->tableWidget->cursor());
        qDebug() << "added";
    }
    if (obj == ui->tableWidget && event->type() == QEvent::Leave)
    {
        qApp->restoreOverrideCursor();
    }
    return QObject::eventFilter(obj, event);
}

答案 1 :(得分:0)

horizo​​ntalHeader() - &gt; setSectionResizeMode(i,QHeaderView :: Fixed);