在QT表格中添加按鈕,可以通過以下步驟實現:
下面是一個簡單的示例代碼:
#include <QtWidgets>
class CustomTableModel : public QAbstractTableModel
{
public:
int rowCount(const QModelIndex& parent = QModelIndex()) const override
{
return 3;
}
int columnCount(const QModelIndex& parent = QModelIndex()) const override
{
return 3;
}
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override
{
if (role == Qt::DisplayRole) {
return QString("Row %1, Column %2").arg(index.row() + 1).arg(index.column() + 1);
}
return QVariant();
}
Qt::ItemFlags flags(const QModelIndex& index) const override
{
Qt::ItemFlags flags = QAbstractTableModel::flags(index);
if (index.isValid() && index.column() == 2) {
flags |= Qt::ItemIsEnabled | Qt::ItemIsSelectable;
flags |= Qt::ItemIsEnabled;
}
return flags;
}
bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) override
{
if (role == Qt::EditRole) {
if (index.isValid() && index.column() == 2) {
emit buttonClicked(index.row());
return true;
}
}
return false;
}
void setButton(int row, const QString& text)
{
QModelIndex index = createIndex(row, 2);
setData(index, text, Qt::EditRole);
}
signals:
void buttonClicked(int row);
};
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget* parent = nullptr)
: QMainWindow(parent)
{
QTableView* tableView = new QTableView(this);
setCentralWidget(tableView);
CustomTableModel* model = new CustomTableModel(this);
tableView->setModel(model);
connect(model, &CustomTableModel::buttonClicked, this, &MainWindow::handleButtonClicked);
}
private slots:
void handleButtonClicked(int row)
{
qDebug() << "Button clicked in row" << row + 1;
}
};
以上代碼創建了一個3行3列的表格,最后一列中的單元格可以顯示文本,并且當點擊這些單元格時會觸發一個信號。在主窗口類的槽函數中處理按鈕點擊事件。