问题
Is there any way to disallow any characters except numbers (0-9) in a QTableWidget? For QLineEdits I'm using a RegEx validator, but this is not available for QTableWidgets. I thought of inserting QLineEdits in as CellWidgets into the table, but then I had to rewrite an extreme large amount of functions in my code. So, is there any other (direct) way to do so?
回答1:
I would suggest using an item delegate for your table widget to handle the possible user input. Below is a simplified solution.
The implementation of item delegate:
class Delegate : public QItemDelegate
{
public:
QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem & option,
const QModelIndex & index) const
{
QLineEdit *lineEdit = new QLineEdit(parent);
// Set validator
QIntValidator *validator = new QIntValidator(0, 9, lineEdit);
lineEdit->setValidator(validator);
return lineEdit;
}
};
Implementation of the simple table widget with the custom item delegate:
QTableWidget tw;
tw.setItemDelegate(new Delegate);
// Add table cells...
tw.show();
来源:https://stackoverflow.com/questions/22708623/qtablewidget-only-numbers-permitted