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即可
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!