设置QTableWidget的左上角CornerWidget的文字(一)

来源:互联网 发布:计算机技术与软件 证书 编辑:程序博客网 时间:2024/05/19 22:02
//mainwindow.h
#ifndef MAINWINDOW_H#define MAINWINDOW_H#include <QMainWindow>namespace Ui {class MainWindow;}class MainWindow : public QMainWindow{    Q_OBJECTpublic:    explicit MainWindow(QWidget *parent = 0);    ~MainWindow();    void init();protected:    bool eventFilter(QObject *o, QEvent *e);private:    Ui::MainWindow *ui;};#endif // MAINWINDOW_H
//mainwindow.cpp
#include "mainwindow.h"#include "ui_mainwindow.h"#include <QDebug>#include <QStylePainter>#include <QAbstractButton>MainWindow::MainWindow(QWidget *parent) :    QMainWindow(parent),    ui(new Ui::MainWindow){    ui->setupUi(this);    init();}MainWindow::~MainWindow(){    delete ui;}void MainWindow::init(){    QAbstractButton* btn = findChild<QAbstractButton*>();    if (btn)    {        btn->setText("ID");        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())            ui->tableWidget->verticalHeader()->setMinimumWidth(s.width());    }}bool MainWindow::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;}
0 0
原创粉丝点击