关于QListWidget自定义Item的学习

直接上代码,

        QListWidget *listWidget = new QListWidget;
        QWidget *widget = new QWidget;
        QListWidgetItem *item = new QListWidgetItem(listWidget );
        listWidget->addItem(nitem);
        nitem->setSizeHint(QSize(0,50));
        ui->listWidget->setItemWidget(nitem,widget);

上面的代码是实现将widget设置为listWidget的Item,
需要对item自定义的话,直接重新封装一个继承于QWidget的类就可以了,下面贴出我的相关代码,供参考:


ProjectDialog::ProjectDialog(QString path,QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ProjectDialog)
{
    ui->setupUi(this);

    //获取所有的文件夹
    QDir dir(path);
    m_path = path;
    dir.setFilter(QDir::Dirs);

    foreach(QFileInfo fullDir, dir.entryInfoList())
    {
        if(fullDir.fileName() == "." || fullDir.fileName() == "..") continue;

        QWidget *widget = createItemWidget(fileName);
        QListWidgetItem *item = new QListWidgetItem(ui->listWidget);
        ui->listWidget->addItem(item);
        item->setSizeHint(QSize(0,50));
        ui->listWidget->setItemWidget(item,widget);
    }
}

ProjectDialog::~ProjectDialog()
{
    delete ui;
}

QWidget *ProjectDialog::createItemWidget(QString projectName)
{
    QFont font;
    font.setPixelSize(18);

    QWidget *widget = new QWidget;
    widget->setMinimumHeight(40);
    QHBoxLayout *layout = new QHBoxLayout(widget);


    QLabel *lab_name = new QLabel(this);
    lab_name->setMinimumHeight(30);
    lab_name->setFont(font);
    lab_name->setText(QStringLiteral("名称:"));

    QLabel *lab_projectName = new QLabel(widget);
    lab_projectName->setStyleSheet("border-width: 1px;border-style: solid;border-color: rgb(0, 0, 0);");
    lab_projectName->setText(projectName);
    lab_projectName->setAlignment(Qt::AlignCenter);
    lab_projectName->setMinimumSize(120,30);
    lab_projectName->setFont(font);


    QToolButton *btn_info = new QToolButton(widget);
    btn_info->setMinimumSize(60,30);
    btn_info->setText(QStringLiteral("文件详情"));
    btn_info->setToolTip(QStringLiteral("文件详情"));
    btn_info->setFocusProxy(this);
    btn_info->setFont(font);


    QToolButton *btn_selected = new QToolButton(widget);
    btn_selected->setMinimumSize(60,30);
    btn_selected->setText(QStringLiteral("选择"));
    btn_selected->setToolTip(QStringLiteral("选择"));
    btn_selected->setFont(font);


    QToolButton *btn_export = new QToolButton(widget);
    btn_export->setMinimumSize(60,30);
    btn_export->setText(QStringLiteral("导出到U盘"));
    btn_export->setToolTip(QStringLiteral("导出到U盘"));
    btn_export->setFont(font);


    layout->addWidget(lab_name,0,Qt::AlignCenter);
    layout->addWidget(lab_projectName,0,Qt::AlignCenter);
    layout->addWidget(btn_info,0,Qt::AlignCenter);
    layout->addWidget(btn_selected,0,Qt::AlignCenter);
    layout->addWidget(btn_export,0,Qt::AlignCenter);

    widget->setLayout(layout);
    return widget;
}

这里面的createItemWidget函数返回一个QWidget类指针,可以直接使用,一般最好还是封装一个Widget类比较好点,这样相对来说灵活点。

你可能感兴趣的:(Qt)