我写了一个在Windows中看起来像记事本的记事本。如何设置为在QTextEdit为空时禁用查找操作但在其中有内容时启用
您将基于文本编辑plainText()
启用/禁用操作的功能连接到文本编辑的textChanged()
信号。
例如:
void MyWidget::someSetupMethod()
{
// ... some code that sets up myTextEdit and myFindAction here
connect(myTextEdit, &QTextEdit::textChanged, myFindAction, [myTextEdit, myFindAction]() {
myFindAction->setEnabled(!myTextEdit->plainText().isEmpty());
});
// ...
}
或者,如果你不能或不想使用C ++ 11,那就像
void MyWidget::someSetupMethod()
{
// ... some code that sets up m_myTextEdit and m_myFindAction here
connect(m_myTextEdit, &QTextEdit::textChanged, this, &MyWidget::updateFindAction);
// ...
}
void MyWidget::updateFindAction()
{
m_myFindAction->setEnabled(!m_myTextEdit->plainText().isEmpty());
}
myTextEdit->plainText().isEmpty()
过程似乎不是非常有效:plainText
方法需要将完整的QTextEdit内容转换为新的QString缓冲区,如果QTextEdit包含大量文本,这是很昂贵的。
我建议使用myTextEdit->document()->isEmpty()
来查询QTextDocument存储,即原始数据结构。
在我的用例中,QTextEdit包含一个错误日志,在附加一行之前,我检查文本是否为空;如果没有,我插入换行符(*)。每次添加一行时将日志缓冲区转换为QString都是个坏主意。
(*)我无法在每个日志条目中插入换行符,因为条目本身是以逗号分隔的列表。粗略地说我有newEntry(...)
和newLine(...)
函数,newEntry
不知道接下来会调用newLine
或newEntry
。