Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Creating a context menu when user selects text



  • I'm making a text editor and one aim is to create a context menu that appears when the user selects/highlights text with their mouse which will bring some further options. It is important that I can read the text the user selects into some other QString object.

    So far, I have attempted to do this repeatedly with an override to mousePressEvent and mouseReleaseEvent in order to position the QTextCursor appropriately in the document and select the text.

    The code is as follows:

    void MainWindow::mousePressEvent(QMouseEvent *event)
    {
        if (event->button() == Qt::LeftButton)
            qDebug() << "left button clicked";
        if (event->button() == Qt::RightButton)
            qDebug() << "right button clicked";
        txtcur = ui->textEdit->cursorForPosition(event->pos());
        txtcur.setPosition(txtcur.selectionStart(), QTextCursor::MoveAnchor);
        qDebug() << txtcur.anchor();
    }
    
    void MainWindow::mouseReleaseEvent(QMouseEvent *event)
    {
        txtcur = ui->textEdit->cursorForPosition(event->pos());
        txtcur.setPosition(txtcur.selectionEnd(), QTextCursor::KeepAnchor);
        txtcur.select(QTextCursor::WordUnderCursor);
        if (txtcur.hasSelection())
        {
            qDebug() << "text selected";
            qDebug() << "text selected";
            // create context menu
        }
    }
    

    After some testing, I found that my left clicks in the QTextEdit widget are being ignored or consumed by some other function which is preventing me from selecting the text, while right clicks appear to work fine and I can move the QTextCursor's position but obviously cannot select anything.

    I'm not sure how to proceed if this approach doesn't work, so any advice would be quite appreciated.

    Thanks.



  • Sorry for posting, figured it out on my own 10 minutes later using the emitted signal from the textEdit window selectionChanged() using this very simple code:

    void MainWindow::on_textEdit_selectionChanged()
    {
    QTextCursor txtcur(ui->textEdit->textCursor());
    txtcur.selectionStart();
    txtcur.selectionEnd();
    txtSelected = txtcur.selectedText();
    qDebug() << txtSelected;
    }
    I still don't understand what was consuming the left click event on textEdit but at least its working now.



  • @Grudy said in Creating a context menu when user selects text:

    its working now.

    great! so if your issue is solved, please don't forget to mark your post as such.


Log in to reply