Qt QTableView滑动、居中、选中加粗

目录

1.效果:

2.滑动

3.居中

4.选中加粗

5.使用的样式表


1.效果:

 

2.滑动

在使用触控屏时需要列表或视图能够滑动查看

ui->tableView->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
QScroller* scroller = QScroller::scroller(ui->tableView->viewport());
scroller->grabGesture(ui->tableView>viewport(),QScroller::LeftMouseButtonGesture);

为滚动区域注册了 鼠标左键的手势识别器,在触摸屏上时可以设置为 QScroller::TouchGesture

触摸手势,很多view都可以实现滑动:QListView,QComboBox下拉框滑动...

也可以自己配置滚动属性:具体属性和值范围可以直接跳转帮助文档查看。

QScrollerProperties properties = scroller->scrollerProperties();
    properties.setScrollMetric(QScrollerProperties::DragVelocitySmoothingFactor,0.1);
    properties.setScrollMetric(QScrollerProperties::FrameRate,QScrollerProperties::Fps60);
scroller->setScrollerProperties(properties);

3.居中

3.1 继承 QSqlQueryModel 重写data函数实现表格数据居中

class MySqlQueryModel : public QSqlQueryModel

QVariant data(const QModelIndex &item, int role=Qt::DisplayRole) const;

QVariant MySqlQueryModel::data(const QModelIndex & index, int role) const
{
    if(role == Qt::TextAlignmentRole){
        QVariant value = Qt::AlignCenter;
        return value;
    }
    return QSqlQueryModel::data(index,role);
}

3.2 自定义代理实现表格数据居中

class MyDelegate : public QStyledItemDelegate

void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;

void MyDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionViewItem newoption(option);
    newoption.displayAlignment = Qt::AlignCenter;        // 居中显示
    QStyledItemDelegate::paint(painter, newoption, index);
}

4.选中加粗

同上,如果是选中状态,则字体加粗

void MyDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionViewItem new_option(option);
    new_option.displayAlignment = Qt::AlignCenter;        // 居中显示
    
    if (new_option.state & QStyle::State_Selected) {
        new_option.font.setBold(true);                    // 变为粗体
    }
    QStyledItemDelegate::paint(painter, new_option, index);
}

/*使用*/
MyDelegate * deldgate = new MyDelegate();
ui->tableView->setItemDelegate(deldgate);

5.使用的样式表

QHeaderView::section {
font: 20px "微软雅黑";
font-weight:bold;
color: rgb(24, 100, 249);
padding-left: 4px;
border: 1px solid #e2e2e2;
background-color:#cddffe;
}

QTableView{
border:none;
color: rgb(119, 119, 119);
gridline-color:#e2e2e2;
}

QTableView::item::selected{
background-color:#cddffe;
color:rgb(51, 51, 51);
}

/*QTableView 左上角样式*/
QTableView QTableCornerButton::section {
background-color:#cddffe;
border: 1px solid #e2e2e2;
}

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值