QTableWidget左上角添加按钮

网友投稿 1634 2022-11-30

QTableWidget左上角添加按钮

QTableWidget左上角添加按钮

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

GTableWidget.h

#ifndef GTABLEWIDGET_H#define GTABLEWIDGET_H#include class TableWidget : public QTableWidget{ Q_OBJECTpublic: TableWidget(int rows, int cols, QWidget* parent = 0); bool eventFilter(QObject* o, QEvent* e);};#endif // GTABLEWIDGET_H

#include "GTableWidget.h"#include #include #include #include #include TableWidget::TableWidget(int rows, int cols, QWidget *parent) : QTableWidget(rows, cols, parent){ QAbstractButton* btn = findChild(); 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(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 #include 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;}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:qt多个窗口排列
下一篇:Qt画k线图
相关文章

 发表评论

暂时没有评论,来抢沙发吧~