Nominate our 2022 Qt Champions!

Set row highlighted when application start in QTableWidget

  • Hello devs!

    I am currently trying to develop an application where I have a QTableWidget.
    This tableWidget has 2 columns (containing text).
    The selection behaviour is set to "QAbstractItemView::SelectRows" - which selects the entire row instead of the single cell.
    Now I'm trying to set the first row as highlighted when my application is launched. I have had no luck so far though.

    Can anyone help me out?

    Thank you for your time.

  • You can use "void QTableWidget::setCurrentCell ( int row, int column )": with selection mode set to QAbstractItemView::SingleSelection or QAbstractItemView::ExtendedSelection

  • That doesn't work for me. Guess it has something to do with me selecting an entire row?

  • When do you call this method?
    If you do it in the constructor, it will not work, as the input focus has not moved there...

  • Yes, I call my QTableWidget setup method from the constructer.

    Here is some of my code:
    Setup::Setup(QWidget *parent) :
    Parent_ui(parent) {


    void Setup::populateList() {

    ui.tableWidget->setColumnWidth(0,(ui.tableWidget->width() - 152));

    ... //items are added to the QTableWidget

    So I cant call setCurrentCell from my populateList method?

    How do I handle this problem?

    Thank you for your time!

    Edit: Please use @ tags to format code sections; Andre

  • No, you can not. The problem is, that at that time, your form is not even showing yet.
    What you might do, is something like this:

    Setup::Setup(QWidget *parent) :
    Parent_ui(parent) {

    //trigger 2nd phase of initialization when the eventloop is running
    QTimer::singleShot(0, this, SLOT(initializePhase2()));

    void Setup::initializePhase2()
    //set which row to highlight.

    Don't forget to mark initializePhase2 as a (private) slot in your header, and include the Q_OBJECT macro in your class definition, of course. Sorry for the inconvenience...

  • bq. Sorry for the inconvenienceā€¦

    I am grateful for your help - that goes to all of you. :)

    The cell row is now highlighted grey - what method could set the row as... hmm.. is it called focus? You know like when you click a cell and it turns blue.

    Again - thank you for your time!

  • Make the table widget have the focus. See QWidget::setFocus().

    BTW: note that there is a difference between the active cell and selected cells. They may be rendered differently.

  • Oh god... I'm sorry for my ignorance.
    I answer my own question in my previous post. Sorry.

Log in to reply