我编写了一个简单的代码来制作一个可选中复选框的组合框。但我看不到可以选中或取消选中的实际复选框,我只看到文本:
这是我的代码:
主窗口.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QStandardItemModel>
#include <QComboBox>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
QStandardItemModel *model;
private slots:
void buttonclicked();
};
#endif // MAINWINDOW_H
主窗口.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <iostream>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->model = new QStandardItemModel(4, 1); // 4 rows, 1 col
for (int r = 0; r < 4; ++r)
{
QStandardItem* item;
if(r == 0)
item = new QStandardItem(QString("All"));
else
item = new QStandardItem(QString("Item %0").arg(r));
item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
item->setData(Qt::Unchecked, Qt::CheckStateRole);
model->setItem(r, 0, item);
}
ui->comboBox->setModel(model);
connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(buttonclicked()));
}
void MainWindow::buttonclicked()
{
unsigned int i;
for(i=0; i<ui->comboBox->count(); i++)
{
QModelIndex index = ui->comboBox->model()->index(i, 0);
QVariant v = index.data(Qt::CheckStateRole);
int j = v.toInt();
if(j == 2)
{
QModelIndex ii = ui->comboBox->model()->index(i, 0);
QString text = ii.data(Qt::DisplayRole).toString();
qDebug() << text;
}
}
qDebug()<<"";
}
MainWindow::~MainWindow()
{
delete ui;
}
主文件
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}