一杯清酒邀明月
天下本无事,庸人扰之而烦耳。
posts - 3121,comments - 209,views - 578万

简言:listview 无论在mfc中还是在Qt中应用是极其广泛的,本节简单进行Qlistview在Qt中操作。

目标:QlistView中插入一段数据,根据点击的相应顺序,弹出列表中的项目。

.h

复制代码
 1 #ifndef MAINWINDOW_H
 2 #define MAINWINDOW_H
 3 
 4 #include <QMainWindow>
 5 #include <QStringListModel>
 6 #include <QStandardItemModel>
 7 #include <QModelIndex>
 8 
 9 namespace Ui {
10 class MainWindow;
11 }
12 
13 class MainWindow : public QMainWindow
14 {
15     Q_OBJECT
16 
17 public:
18     explicit MainWindow(QWidget *parent = 0);
19     ~MainWindow();
20 
21 private:
22     Ui::MainWindow *ui;
23 
24 public:
25     QStringListModel *Model;
26     QStandardItemModel *ItemModel;
27     void init();
28 
29 private slots:
30     void showClick(QModelIndex index);
31 };
32 
33 #endif // MAINWINDOW_H
复制代码

.cpp

复制代码
 1 #include "mainwindow.h"
 2 #include "ui_mainwindow.h"
 3 #include <QMessageBox>
 4 
 5 MainWindow::MainWindow(QWidget *parent) :
 6     QMainWindow(parent),
 7     ui(new Ui::MainWindow)
 8 {
 9     ui->setupUi(this);
10     init();
11 }
12 
13 void MainWindow::init()
14 {
15 //     QStringList strlist;
16 //     strlist<<"A"<<"B"<<"C"<<"D";
17 //     Model = new QStringListModel(strlist);
18 //     ui->listView->setModel(Model);
19 //     ui->listView->setModel(Model);
20 
21        ItemModel = new QStandardItemModel(this);
22 
23        QStringList strList;
24        strList.append("A");
25        strList.append("B");
26        strList.append("C");
27        strList.append("D");
28        strList.append("E");
29        strList.append("F");
30        strList.append("G");
31 
32        int nCount = strList.size();
33        for(int i = 0; i < nCount; i++)
34        {
35            QString string = static_cast<QString>(strList.at(i));
36            QStandardItem *item = new QStandardItem(string);
37            ItemModel->appendRow(item);
38        }
39       ui->listView->setModel(ItemModel);
40       ui->listView->setFixedSize(200,300);
41 
42       connect(ui->listView,SIGNAL(clicked(QModelIndex)),this,SLOT(showClick(QModelIndex)));
43 }
44 
45 void MainWindow::showClick(QModelIndex index)
46 {
47     QString strTemp;
48     strTemp = index.data().toString();
49 
50     QMessageBox msg;
51     msg.setText(strTemp);
52     msg.exec();
53 
54 
55 }
56 MainWindow::~MainWindow()
57 {
58     delete ui;
59 }
复制代码

实现效果:
这里写图片描述

这里写图片描述

总结:此为Qlistview在Qt应用中的简单使用

posted on   一杯清酒邀明月  阅读(3360)  评论(0编辑  收藏  举报
编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示