Search code examples
c++qtcropqmessagebox

How to crop text in a QComboBox or how to get its actual width?


I want to crop a text in a QComboBox. But for this, I need to know the width of a QComboBox. And when I call something like this:

ui->qcombobox->width() 

I get incorrect value (actual width is about 260 px but the resulting width is always 100 px).

Questions:

How can I get real width of a QComboBox ?

OR

How can I crop text depends on a QComboBox width?


Solution

  • You are calling ui->qcombobox->width() in a constructor. Combobox's size is not calculated on this step yet. You need to wait until the first showEvent occures. Try something like this:

    void MainWindow::showEvent(QShowEvent *e)
    {
        QMainWindow::showEvent(e);
        qDebug() << ui->qcombobox->width();
    }
    

    In order to fill combobox on creating widget you need to do something like this:

    void MainWindow::showEvent(QShowEvent *e)
    {
        QMainWindow::showEvent(e);
        if (!mWasFilled) {
            mWasFilled = true;
            fillCombobox();
        }
    }