Add ``setValidator`` method to widget instances that receive input
hankadler opened this issue · comments
It'd be great if widgets that accept user input like QLineEdit
instances implemented a setValidator
method that accepted a function that prohibits input for which it evaluates to false.
For an example of how this is done in PyQt see here.
In JavaScript nodegui it could look something like this:
const { isFloat } = require("validator"); // i.e. validator from npm
//...
const widthLineEdit = new QLineEdit();
widthLineEdit.setPlaceholderText("0.0");
widthLineEdit.setValidator(isFloat)
//...
In the meantime I'm open to workaround suggestions (
setInputMask
, etc.), I've only just started playing around with nodegui, but so far I'm liking it. Please keep it going. Thank you!
Here's how I'm solving this at the moment:
// utils/filters.ts
export function filterFloat(text: string): string {
return text
.replace(/[^\d.-]/g, "")
.replace(/(?<=\..*)\./g, "")
.replace(/(?<=-.*)-/g, "");
}
export function filterUnsignedFloat(text: string): string {
return text
.replace(/[^\d.]/g, "")
.replace(/(?<=\..*)\./g, "");
}
// areaCalculator.ts
// ...
import { filterUnsignedFloat } from "../utils/filters";
// ...
const widthLineEdit = new QLineEdit();
widthLineEdit.setPlaceholderText("0.0");
widthLineEdit.addEventListener(
"textChanged", (text) => widthLineEdit.setText(filterUnsignedFloat(text))
);