QTableWidget: Only numbers permitted

大城市里の小女人 提交于 2019-12-11 01:26:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!