c++ - QTableView自动调整行高

标签 c++ postgresql qt qtableview

我有一个派生自 QTableView (Qt 5.5.1) 的小部件,用于显示来自 Postgres 服务器的数据。我想在用户使用鼠标调整列大小时自动将行高调整为自动换行的内容:

MyTableView::MyTableView(QWidget *parent) : QTableView(parent)
{
    //  ...
    connect(
        horizontalHeader(),
        SIGNAL(sectionResized(int, int, int)),
        this,
        SLOT(resizeRowsToContents()));
}

这非常适用于小表,但由于速度较慢,较大的表实际上不适合使用。我需要一个类似 afterSectionResized 的信号(当鼠标释放完成调整大小时),但没有这样的事件。

当用户使用鼠标调整列大小时,如何避免出现多个表格格式?

最佳答案

定义一个派生自 QHeaderView 的新类 (MyHeaderView) 和一个新信号 (resized()) 当用户在调整部分大小后释放鼠标按钮时发出。

myheaderview.h

class MyHeaderView : public QHeaderView
{
    Q_OBJECT

public:
    explicit MyHeaderView(QWidget *parent = 0);

signals:
    void resized();

private:
    bool resizing;
    void mouseReleaseEvent(QMouseEvent *);

private slots:
    void setResizing();
};

myheaderview.cpp

MyHeaderView::MyHeaderView(QWidget *parent)
    : QHeaderView(Qt::Horizontal, parent)
{
    resizing = false;
    connect(this,
            SIGNAL(sectionResized(int, int, int)),
            this,
            SLOT(setResizing()));
}

void MyHeaderView::setResizing()
{
    resizing = true;
}

void MyHeaderView::mouseReleaseEvent(QMouseEvent *)
{
    if (resizing) {
        resizing = false;
        emit resized();
    }
}

MyTableView 类中用定义的标题小部件替换标准水平标题:

MyTableView::MyTableView(QWidget *parent) : QTableView(parent)
{
    myHeaderView = new MyHeaderView(this);
    setHorizontalHeader(myHeaderView);
    connect(horizontalHeader(),
            SIGNAL(resized()),
            this,
            SLOT(resizeRowsToContents()));
}

关于c++ - QTableView自动调整行高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33892528/

相关文章:

c++ - 如何让我的服务器应用程序使用我的 IP 地址而不是本地主机

c++ - TFTP数据包

Python 网络服务来 self 的 Postgres 数据库的 JSON 提要

mysql - 从 postgresql 转储文件填充 MySQL 数据库

c++ - DLL链接到静态库

c++ - 我应该使用冒泡排序、插入排序等排序算法,还是应该使用 C++ 中内置的 sort() 函数对数组进行排序?

sql - Postgres json 在一行中获取结果

c++ - 如何拆分大型 qmainwindow 代码(如有必要)?

c++ - 可以在 OSx 中使 QDialog 抖动

c++ - 在 Qt 安装程序框架中禁用 native 下一步按钮