QTableView设置表格左上的文字主要方法是继承后添加按钮

QTableWidget左上角添加按钮_qt


GTableWidget.h

#ifndef GTABLEWIDGET_H
#define GTABLEWIDGET_H


#include <QTableWidget>

class TableWidget : public QTableWidget
{
Q_OBJECT

public:
TableWidget(int rows, int cols, QWidget* parent = 0);

bool eventFilter(QObject* o, QEvent* e);

};


#endif // GTABLEWIDGET_H
#include "GTableWidget.h"

#include <QEvent>
#include <QHeaderView>
#include <QApplication>
#include <QStylePainter>
#include <QAbstractButton>

TableWidget::TableWidget(int rows, int cols, QWidget *parent)
: QTableWidget(rows, cols, parent)
{
QAbstractButton* btn = findChild<QAbstractButton*>();

if (btn)
{
btn->setText(QStringLiteral("角落按钮"));
btn->installEventFilter(this);

// adjust the width of the vertical header to match the preferred corner button width

// (unfortunately QAbstractButton doesn't implement any size hinting functionality)

QStyleOptionHeader opt;
opt.text = btn->text();
QSize s = (btn->style()->sizeFromContents(QStyle::CT_HeaderSection, &opt, QSize(), btn).
expandedTo(QApplication::globalStrut()));

if (s.isValid())
{
verticalHeader()->setMinimumWidth(s.width());
}
}
}


bool TableWidget::eventFilter(QObject *o, QEvent *e)
{
if (e->type() == QEvent::Paint)
{
QAbstractButton* btn = qobject_cast<QAbstractButton*>(o);

if (btn)
{
// paint by hand (borrowed from QTableCornerButton)

QStyleOptionHeader opt;
opt.init(btn);
QStyle::State state = QStyle::State_None;

if (btn->isEnabled())
{
state |= QStyle::State_Enabled;
}

if (btn->isActiveWindow())
{
state |= QStyle::State_Active;
}

if (btn->isDown())
{
state |= QStyle::State_Sunken;
}

opt.state = state;
opt.rect = btn->rect();
opt.text = btn->text(); // this line is the only difference to QTableCornerButton

opt.position = QStyleOptionHeader::OnlyOneSection;
QStylePainter painter(btn);
painter.drawControl(QStyle::CE_Header, opt);
return true; // eat event
}
}

return false;
}

测试

#include "mainwindow.h"
#include "GTableWidget.h"
#include "ui_mainwindow.h"
#include <QHeaderView>
#include <QVBoxLayout>

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

TableWidget *pTableWidget = new TableWidget(3, 3,this);
pTableWidget->setStyleSheet("QTableCornerButton::section{background-color: red;}");
pTableWidget->horizontalHeader()->setStyleSheet("QHeaderView::section{background: green}");
pTableWidget->verticalHeader()->setStyleSheet("QHeaderView::section{background: green}");

QVBoxLayout *pLayout = new QVBoxLayout(this);
pLayout->addWidget(pTableWidget);

ui->centralWidget->setLayout(pLayout);
}

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