QT textedit如何限定输入字数
答案:2 悬赏:30 手机版
解决时间 2021-02-04 16:58
- 提问者网友:愿为果
- 2021-02-03 16:05
QT textedit如何限定输入字数
最佳答案
- 五星知识达人网友:冷風如刀
- 2021-02-03 17:40
方法一:
mEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(Constants.MAX_TEXT_INPUT_LENGTH)});
方法二:
private TextWatcher mTextWatcher = new TextWatcher(){
Toast mToast = null;
public void beforeTextChanged(CharSequence s, int start,
int count,int after) {
}
public void onTextChanged(CharSequence s, int start,
int before,int count) {
}
public void afterTextChanged(Editable s) {
int nSelStart = 0;
int nSelEnd = 0;
boolean nOverMaxLength = false;
nSelStart = mEditText.getSelectionStart();
nSelEnd = mEditText.getSelectionEnd();
nOverMaxLength = (s.length() > Constants.MAX_TEXT_INPUT_LENGTH) ? true : false;
if(nOverMaxLength){
if(null == mToast){
mToast = Toast.makeText(mContext,
R.string.IDS_MSG_TEXT_OVER_MAXLENGTH,
Toast.LENGTH_SHORT);
}
mToast.show();
s.delete(nSelStart - 1, nSelEnd);
mEditText.setTextKeepState(s);//请读者注意这一行,保持光标原先的位置,而 mEditText.setText(s)会让光标跑到最前面,
//就算是再加mEditText.setSelection(nSelStart) 也不起作用
}
}
};
mEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(Constants.MAX_TEXT_INPUT_LENGTH)});
方法二:
private TextWatcher mTextWatcher = new TextWatcher(){
Toast mToast = null;
public void beforeTextChanged(CharSequence s, int start,
int count,int after) {
}
public void onTextChanged(CharSequence s, int start,
int before,int count) {
}
public void afterTextChanged(Editable s) {
int nSelStart = 0;
int nSelEnd = 0;
boolean nOverMaxLength = false;
nSelStart = mEditText.getSelectionStart();
nSelEnd = mEditText.getSelectionEnd();
nOverMaxLength = (s.length() > Constants.MAX_TEXT_INPUT_LENGTH) ? true : false;
if(nOverMaxLength){
if(null == mToast){
mToast = Toast.makeText(mContext,
R.string.IDS_MSG_TEXT_OVER_MAXLENGTH,
Toast.LENGTH_SHORT);
}
mToast.show();
s.delete(nSelStart - 1, nSelEnd);
mEditText.setTextKeepState(s);//请读者注意这一行,保持光标原先的位置,而 mEditText.setText(s)会让光标跑到最前面,
//就算是再加mEditText.setSelection(nSelStart) 也不起作用
}
}
};
全部回答
- 1楼网友:woshuo
- 2021-02-03 18:17
连接document ()的contentschange信号:
void qtextdocument::contentschange ( int position, int charsremoved, int charsadded ) [signal]
this signal is emitted whenever the document's content changes; for example, when text is inserted or deleted, or when formatting is applied.
information is provided about the position of the character in the document where the change occurred, the number of characters removed (charsremoved), and the number of characters added (charsadded).
the signal is emitted before the document's layout manager is notified about the change. this hook allows you to implement syntax highlighting for the document.
see also qabstracttextdocumentlayout::documentchanged() and contentschanged().
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯