c++ - 为什么slot函数调用成功也无法插入文本

标签 c++ qt text qscintilla

我正在使用 QScintilla 在 Qt 中编写代码编辑器。

我想在输入前括号时自动补全后括号。这样我就可以将 cursorPositionChanged(int, int) 信号连接到 complete_braces() 插槽并且连接正常。但是即使调用了槽函数,insert() 语句也不起作用。

  • 这适用于运行 Qt 5.13.0(MinGW 7.3.0 32 位)、Qt Creator 4.9.2、QScintilla 2.11.2 的 Windows 10 PC。
  • qDebug()语句输出正确,信号槽连接成功。
  • 当我将工具栏按钮触发器连接到槽函数并按下按钮时。后支架放置正确。
  • 当我在普通函数中调用它时,insert(QString) 函数起作用。

标题:

/* codeeditor.h */
class CodeEditor : public QsciScintilla
{
    Q_OBJECT
...

public slots:
    void complete_brackets();
...
};

代码:

/* codeeditor.cpp */
CodeEditor::CodeEditor()
{
...
    // Slots
    connect(this, SIGNAL(textChanged()),
            this, SLOT(complete_brackets()));
...
}
...
void CodeEditor::complete_brackets()
{
    int line, index;
    getCursorPosition(&line, &index);
    if (text(line)[index] == '(')
    {
        qDebug() << "Get a bracket"; // This statement works.
        insert(QString(")")); // This statement doesn't work.
    }
}
...

我希望插槽函数中的 insert(QString) 函数被正确调用,但它没有。

如何使插入语句生效,或者是否有任何其他方法可以自动完成括号?

最佳答案

似乎 QsciScintilla 不允许在连接到 textChanged 信号的插槽中添加文本,一个可能的解决方案是稍后使用 添加它QTimer::singleShot():

void CodeEditor::complete_brackets(){
    int line, index;
    getCursorPosition(&line, &index);
    if (text(line)[index] == '(')
        QTimer::singleShot(0, [this, line, index](){
          insert(")");
          setCursorPosition(line, index+2);
        });
}

另一方面,建议您使用新的连接语法:

connect(this, &QsciScintilla::textChanged, this, &CodeEditor::complete_brackets);

关于c++ - 为什么slot函数调用成功也无法插入文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57234665/

相关文章:

c++ - 为什么我的qt程序卡住了?

c++ - Qt Creator 程序因使用 taglib 而崩溃

php - XPath 和 PHP : Matching text after a <br>

c++ - 为什么在这段代码片段中复制构造函数被调用了两次?

c++ - 是否可以使用编译时计算将 C/C++ 结构填充到固定大小?

qt - 如何制作非阻塞、非模态的 QMessageBox?

c# - C#读取txt文件

c++ - 如何使用 C++ 使用 ODBC 驱动程序 API 将数据绑定(bind)到 SQLBindCol

c++ - 将 'std::cin' 与数据结构成员一起使用

Java:如何将绘制的文本动态地适合窗口