如何与复选框操作交互? (QTableView 与 QStandardItemModel)

发布于 2024-08-31 14:20:15 字数 494 浏览 6 评论 0原文

我正在使用 QTableView 和 QStandardItemModel 来显示一些数据。

对于每一行,有一列有一个复选框,这个复选框是通过setItem插入的,代码如下:

int rowNum;
QStandardItemModel *tableModel;
QStandardItem* __tmpItem = new QStandardItem();

__tmpItem->setCheckable(true);
__tmpItem->setCheckState(Qt::Unchecked);

tableModel->setItem(rowNum,0,__tmpItem);

现在我想与该复选框进行交互。如果用户更改复选框的状态(从选中变为未选中,反之亦然),我想对相应的数据行执行某些操作。

我知道我可以使用信号槽来捕获复选框的变化,但是由于数据行很多,我不想将每一行一一连接。

有没有办法更有效地与检查操作交互?谢谢 :)

I'm using QTableView and QStandardItemModel to show some data.

For each row, there is a column which has a check Box, this check box is inserted by setItem, the code is as follows:

int rowNum;
QStandardItemModel *tableModel;
QStandardItem* __tmpItem = new QStandardItem();

__tmpItem->setCheckable(true);
__tmpItem->setCheckState(Qt::Unchecked);

tableModel->setItem(rowNum,0,__tmpItem);

Now I want to interact with the check box. If a check box changes its state by user (from checked to unchecked or vice versa), I want to do something on the corresponding data row.

I know I can use signal-slot to catch the change of checkbox, but since there are lots of data row, I don't want to connect each row one by one.

Is there anyway to interact with the check action more effectively? Thanks :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

女皇必胜 2024-09-07 14:20:15

我不处理 QTableView+QStandardItemModel,但下面的示例可能会对您有所帮助:

1)。表.h 文件:

#ifndef TABLE__H
#define TABLE__H

#include <QtGui>

class ItemDelegate : public QItemDelegate
{
public:
    ItemDelegate(QObject *parent = 0)
        : QItemDelegate(parent)
    {
    }
    virtual void drawCheck(QPainter *painter, const QStyleOptionViewItem &option,
        const QRect &, Qt::CheckState state) const
    {
        const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;

        QRect checkRect = QStyle::alignedRect(option.direction, Qt::AlignCenter,
            check(option, option.rect, Qt::Checked).size(),
            QRect(option.rect.x() + textMargin, option.rect.y(),
            option.rect.width() - (textMargin * 2), option.rect.height()));
        QItemDelegate::drawCheck(painter, option, checkRect, state);
    }
    virtual bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option,
        const QModelIndex &index)
    {
        Q_ASSERT(event);
        Q_ASSERT(model);

        // make sure that the item is checkable
        Qt::ItemFlags flags = model->flags(index);
        if (!(flags & Qt::ItemIsUserCheckable) || !(flags & Qt::ItemIsEnabled))
            return false;
        // make sure that we have a check state
        QVariant value = index.data(Qt::CheckStateRole);
        if (!value.isValid())
            return false;
        // make sure that we have the right event type
        if (event->type() == QEvent::MouseButtonRelease) {
            const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;
            QRect checkRect = QStyle::alignedRect(option.direction, Qt::AlignCenter,
                check(option, option.rect, Qt::Checked).size(),
                QRect(option.rect.x() + textMargin, option.rect.y(),
                option.rect.width() - (2 * textMargin), option.rect.height()));
            if (!checkRect.contains(static_cast<QMouseEvent*>(event)->pos()))
                return false;
        } else if (event->type() == QEvent::KeyPress) {
            if (static_cast<QKeyEvent*>(event)->key() != Qt::Key_Space
                && static_cast<QKeyEvent*>(event)->key() != Qt::Key_Select)
                return false;
        } else {
            return false;
        }
        Qt::CheckState state = (static_cast<Qt::CheckState>(value.toInt()) == Qt::Checked
            ? Qt::Unchecked : Qt::Checked);

        QMessageBox::information(0,
            QString((state == Qt::Checked) ? "Qt::Checked" : "Qt::Unchecked"),
            QString("[%1/%2]").arg(index.row()).arg(index.column()));

        return model->setData(index, state, Qt::CheckStateRole);
    }
    virtual void drawFocus(QPainter *painter, const QStyleOptionViewItem &option, const QRect &rect) const
    {
        QItemDelegate::drawFocus(painter, option, option.rect);
    }
};


static int ROWS = 3;
static int COLS = 1;
class Table : public QTableWidget
{
    Q_OBJECT
public:
    Table(QWidget *parent = 0)
        : QTableWidget(ROWS, COLS, parent)
    {
        setItemDelegate(new ItemDelegate(this));
        QTableWidgetItem *item = 0;
        for (int i=0; i<rowCount(); ++i) {
            for (int j=0; j<columnCount(); ++j) {
                setItem(i, j, item = new QTableWidgetItem);
                item->setFlags(Qt::ItemIsEnabled|Qt::ItemIsUserCheckable);
                item->setCheckState((i+j) % 2 == 0 ? Qt::Checked : Qt::Unchecked);
            }
        }
    }
};

#endif

2). main.cpp 文件:

#include <QApplication>

#include "table.h"

int main(int argc, char **argv)
{
    QApplication a(argc, argv);
    Table w;
    w.show();
    return a.exec();
}

祝你好运。

PS:这是原始的文本

I don't deal with QTableView+QStandardItemModel, but may be example below will help you:

1). table.h file:

#ifndef TABLE__H
#define TABLE__H

#include <QtGui>

class ItemDelegate : public QItemDelegate
{
public:
    ItemDelegate(QObject *parent = 0)
        : QItemDelegate(parent)
    {
    }
    virtual void drawCheck(QPainter *painter, const QStyleOptionViewItem &option,
        const QRect &, Qt::CheckState state) const
    {
        const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;

        QRect checkRect = QStyle::alignedRect(option.direction, Qt::AlignCenter,
            check(option, option.rect, Qt::Checked).size(),
            QRect(option.rect.x() + textMargin, option.rect.y(),
            option.rect.width() - (textMargin * 2), option.rect.height()));
        QItemDelegate::drawCheck(painter, option, checkRect, state);
    }
    virtual bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option,
        const QModelIndex &index)
    {
        Q_ASSERT(event);
        Q_ASSERT(model);

        // make sure that the item is checkable
        Qt::ItemFlags flags = model->flags(index);
        if (!(flags & Qt::ItemIsUserCheckable) || !(flags & Qt::ItemIsEnabled))
            return false;
        // make sure that we have a check state
        QVariant value = index.data(Qt::CheckStateRole);
        if (!value.isValid())
            return false;
        // make sure that we have the right event type
        if (event->type() == QEvent::MouseButtonRelease) {
            const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;
            QRect checkRect = QStyle::alignedRect(option.direction, Qt::AlignCenter,
                check(option, option.rect, Qt::Checked).size(),
                QRect(option.rect.x() + textMargin, option.rect.y(),
                option.rect.width() - (2 * textMargin), option.rect.height()));
            if (!checkRect.contains(static_cast<QMouseEvent*>(event)->pos()))
                return false;
        } else if (event->type() == QEvent::KeyPress) {
            if (static_cast<QKeyEvent*>(event)->key() != Qt::Key_Space
                && static_cast<QKeyEvent*>(event)->key() != Qt::Key_Select)
                return false;
        } else {
            return false;
        }
        Qt::CheckState state = (static_cast<Qt::CheckState>(value.toInt()) == Qt::Checked
            ? Qt::Unchecked : Qt::Checked);

        QMessageBox::information(0,
            QString((state == Qt::Checked) ? "Qt::Checked" : "Qt::Unchecked"),
            QString("[%1/%2]").arg(index.row()).arg(index.column()));

        return model->setData(index, state, Qt::CheckStateRole);
    }
    virtual void drawFocus(QPainter *painter, const QStyleOptionViewItem &option, const QRect &rect) const
    {
        QItemDelegate::drawFocus(painter, option, option.rect);
    }
};


static int ROWS = 3;
static int COLS = 1;
class Table : public QTableWidget
{
    Q_OBJECT
public:
    Table(QWidget *parent = 0)
        : QTableWidget(ROWS, COLS, parent)
    {
        setItemDelegate(new ItemDelegate(this));
        QTableWidgetItem *item = 0;
        for (int i=0; i<rowCount(); ++i) {
            for (int j=0; j<columnCount(); ++j) {
                setItem(i, j, item = new QTableWidgetItem);
                item->setFlags(Qt::ItemIsEnabled|Qt::ItemIsUserCheckable);
                item->setCheckState((i+j) % 2 == 0 ? Qt::Checked : Qt::Unchecked);
            }
        }
    }
};

#endif

2). main.cpp file:

#include <QApplication>

#include "table.h"

int main(int argc, char **argv)
{
    QApplication a(argc, argv);
    Table w;
    w.show();
    return a.exec();
}

Good luck.

PS: here is the original text.

迷途知返 2024-09-07 14:20:15

处理点击事件,在那里你将获得模型索引,获取数据并修改相同的

如果你要插入多个文本或图标,那么你需要为你的列表视图设置委托

handle the click event, there you will get the modelindex, get the data and modify the same

if you are going to insert more than one text or icon, then you need to set the delegate for your listview

我们只是彼此的过ke 2024-09-07 14:20:15

这是 mosg 建议使用 QStyleItemDelegate 代替的示例的另一个类似想法。 http://developer.qt.nokia.com/faq/answer/how_can_i_align_the_checkboxes_in_a_view

Here is another similar idea of the example suggested by mosg using a QStyleItemDelegate instead. http://developer.qt.nokia.com/faq/answer/how_can_i_align_the_checkboxes_in_a_view

旧情别恋 2024-09-07 14:20:15

在单击的插槽和 index.data(Qt::CheckStateRole) 上使用:

void MainWindow::on_tableView_clicked(const QModelIndex &index)
{
    if(index.column() == 2){
        if(index.data(Qt::CheckStateRole) == Qt::Checked){
             //your code 
        }else if(index.data(Qt::CheckStateRole) == Qt::Unchecked){
             //your code
        }
    }
    //get other infos
    QVariant value = index.sibling(index.row(),0).data();
    QString selectedMessageName = value.toString();
}

Use on clicked slot and index.data(Qt::CheckStateRole) :

void MainWindow::on_tableView_clicked(const QModelIndex &index)
{
    if(index.column() == 2){
        if(index.data(Qt::CheckStateRole) == Qt::Checked){
             //your code 
        }else if(index.data(Qt::CheckStateRole) == Qt::Unchecked){
             //your code
        }
    }
    //get other infos
    QVariant value = index.sibling(index.row(),0).data();
    QString selectedMessageName = value.toString();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文