Qt QListView详解

一.常用接口

1.添加数据

    QStringListModel *model;   
    model = new QStringListModel(this);

    model->setStringList(QStringList()<<"语文"<<"数学"<<"英语");


    ui->listView->setModel(model);

2.使用自定义的widget

这里使用QLineEdit来举例,可以使用自定义的widget,图如下,可以看到第二行变成了行编辑框。

    QLineEdit *lineEdit =  new QLineEdit(ui->listView);
    lineEdit->setText("数学");

    ui->listView->setIndexWidget(index,lineEdit);

3.设置默认哪一行选中

QModelIndex index2 = model->index(2);    
ui->listView->setCurrentIndex(index2);

二.信号

以下信号经常使用


void activated(const QModelIndex &index)
void clicked(const QModelIndex &index)
void doubleClicked(const QModelIndex &index)
void entered(const QModelIndex &index)
void pressed(const QModelIndex &index)

简单相应点击的信号,点击后打印text

void Widget::on_listView_clicked(const QModelIndex &index)
{
    qDebug()<<model->data(index).toString();
}

三.右键弹出菜单

    //打开右键菜单属性
    ui->listView->setContextMenuPolicy(Qt::CustomContextMenu);

    //右键菜单
    menu = new QMenu(ui->listView);
    menu->addAction("添加");
    menu->addAction("删除");

    //响应右键菜单信号槽
    connect(ui->listView,&QListView::customContextMenuRequested,
          this,&Widget::slotCustomContextMenuRequested);

    void Widget::slotCustomContextMenuRequested(const QPoint &pos)
    {
        menu->exec(ui->listView->mapToGlobal(pos));
    }

四.设置QSS


QListView 
{
      show-decoration-selected: 1; /* make the selection span the entire width of the view */
}
 
QListView::item:alternate 
{
      background: #EEEEEE;
}
 
QListView::item:selected 
{
      border: 1px solid #6a6ea9;
}
 
QListView::item:selected:!active 
{
      background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                  stop: 0 #ABAFE5, stop: 1 #8588B2);
}
 
QListView::item:selected:active
{
      background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                  stop: 0 #6a6ea9, stop: 1 #888dd9);
}
 
QListView::item:hover
{
      background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                  stop: 0 #FAFBFE, stop: 1 #DCDEF1);
}
//适用于开启交替颜色
QListWidget#listWidget
{
    alternate-background-color:blue;background:yellow
}

调用setStyleSheet即可

五.源码

QListView详解-C++文档类资源-CSDN下载

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

灬Sunnnnn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值