要在 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助手提供,问题来源于学员提问