QT开发中文网

QTableView添加按钮并设置按钮位置和大小C++

要在 QTableView 中添加按钮,并设置按钮的位置和大小,你需要自定义一个代理(QItemDelegate)来绘制按钮。下面是一个简单的示例代码,演示了如何在 QTableView 的某一列中添加按钮:

#include <QApplication>
#include <QStandardItemModel>
#include <QTableView>
#include <QItemDelegate>
#include <QPushButton>

// 自定义代理类
class ButtonDelegate : public QItemDelegate {
public:
    explicit ButtonDelegate(QObject *parent = nullptr)
        : QItemDelegate(parent) {}

    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override {
        // 绘制普通的文本内容
        QItemDelegate::paint(painter, option, index);

        // 获取按钮相关的数据
        QString buttonText = index.data(Qt::DisplayRole).toString();
        QRect buttonRect = option.rect.adjusted(4, 4, -4, -4);

        // 绘制按钮
        QPushButton button(buttonText);
        button.setGeometry(buttonRect);
        QPixmap pixmap = button.grab();
        painter->drawPixmap(buttonRect, pixmap);
    }

    QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override {
        return QSize(100, 30);  // 设置按钮大小
    }
};

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    // 创建模型和视图
    QStandardItemModel model(4, 2);
    model.setHorizontalHeaderLabels({"Name", "Button"});
    for (int row = 0; row < model.rowCount(); ++row) {
      model.setData(model.index(row, 1), "Click");
    }
    
    QTableView tableView;
    tableView.setModel(&model);

    // 设置自定义代理
    ButtonDelegate buttonDelegate;
    tableView.setItemDelegateForColumn(1, &buttonDelegate);

    tableView.show();
    return app.exec();
}

以上示例中,我们通过自定义的 ButtonDelegate 类来绘制按钮。在 paint() 函数中,我们首先调用父类的 paint() 函数以绘制文本内容,然后使用 QPushButton 绘制按钮,并将其绘制到指定位置。sizeHint() 函数可以设置按钮的大小。

你可以根据需要调整按钮的位置和大小,以及对按钮点击事件进行处理。希望这个示例能够帮助你实现在 QTableView 中添加按钮并设置位置和大小。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=6062

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?