的实现。
以下是一个可能的解决方案:
#include <QVBoxLayout>
#include <QPushButton>
#include <QStack>
#include <QWidget>
#include <QTableWidget>
class TableHistory : public QWidget {
Q_OBJECT
public:
explicit TableHistory(QWidget *parent = nullptr);
signals:
private slots:
void onForwardClicked();
void onBackwardClicked();
private:
void addToStack(); // add current table index to stack
void updateButtons(); // update forward/backward button status
QTableWidget *m_table;
QPushButton *m_forwardButton;
QPushButton *m_backwardButton;
QStack<int> m_history; // stack to store table index history
};
TableHistory::TableHistory(QWidget *parent) :
QWidget(parent), m_table(new QTableWidget(this)),
m_forwardButton(new QPushButton("Forward", this)),
m_backwardButton(new QPushButton("Backward", this)) {
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(m_table);
QHBoxLayout *buttonLayout = new QHBoxLayout;
buttonLayout->addWidget(m_backwardButton);
buttonLayout->addWidget(m_forwardButton);
layout->addLayout(buttonLayout);
// connect button signals/slots
connect(m_forwardButton, &QPushButton::clicked, this, &TableHistory::onForwardClicked);
connect(m_backwardButton, &QPushButton::clicked, this, &TableHistory::onBackwardClicked);
// add initial table index to stack
addToStack();
}
void TableHistory::addToStack() {
m_history.push(m_table->currentIndex().row());
if (m_history.size() > 20) { // limit stack size to 20
m_history.pop();
}
updateButtons(); // update button status after adding to stack
}
void TableHistory::updateButtons() {
m_forwardButton->setEnabled(!m_history.isEmpty() && m_history.top() != m_table->rowCount() - 1);
m_backwardButton->setEnabled(m_history.size() > 1);
}
void TableHistory::onForwardClicked() {
// move to next index in stack
int rowIndex = m_history.pop();
m_table->setCurrentCell(rowIndex + 1, 0);
addToStack(); // add new index to stack
}
void TableHistory::onBackwardClicked() {
// move to previous index in stack
m_history.pop();
int rowIndex = m_history.top();
m_table->setCurrentCell(rowIndex, 0);
updateButtons(); // update button status after moving back
}
QTableWidget *TableHistory::getTableWidget() const {
return m_table;
}
使用方法:
TableHistory *tableHistory = new TableHistory(this); // create widget
// add table rows/columns/data
tableHistory->getTableWidget()->setRowCount(5);
tableHistory->getTableWidget()->setColumnCount(2);
for (int row = 0; row < 5; ++row) {
for (int col = 0; col < 2; ++col) {
QTableWidgetItem *item = new QTableWidgetItem(QString("Item %1").arg(row * 2 + col));
tableHistory->getTableWidget()->setItem(row, col, item);
}
}
// add widget to layout
layout()->addWidget(tableHistory);
// access table widget if needed
QTableWidget *table = tableHistory->getTableWidget();