qttext-editorqt-connection

QT connect function for status bar


I'm trying to make a notepad-like app in QT c++, and right now I'm trying to implement a simple status bar that tells the user the Line and the Column of the cursor.

I've been using the connect function like this:

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)

{
    connect(ui->textEdit, SIGNAL(cursorPositionChanged()), this, SLOT(MainWindow::showCursorPosition()));
.
.
}

And I have the showCursorPosition method defined like this:

void MainWindow::showCursorPosition(){
    int line = ui->textEdit->textCursor().blockNumber()+1;
    int column = ui->textEdit->textCursor().columnNumber()+1;
    ui->statusBar->showMessage(QString("Line %1  Column %2").arg(line).arg(column));
}

The method works, I am pretty sure because I called it from the constructor and it shows "Line 1 Column 1" in the status bar.

But the connect function doesn't seem to work properly, and I can't seem to figure out what I've done wrong.


Solution

  • The old (Qt4) syntax doesn't understand C++ namespaces. Change the connect call to...

    connect(ui->textEdit, SIGNAL(cursorPositionChanged()),
            this, SLOT(showCursorPosition()));
    

    Alternatively, if you're using Qt5 you should make use of the newer signal/slot syntax...

    connect(ui->textEdit, &QTextEdit::cursorPositionChanged,
            this, &MainWindow::showCursorPosition);