如何裁剪 QComboBox 中的文本或如何获取其实际宽度?

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

我想在 QComboBox 中裁剪文本。但是为此,我需要知道 QComboBox 的宽度。当我这样调用时:

ui->qcombobox->width() 

我得到的值不正确(实际宽度约为 260 像素,但生成的宽度始终为 100 像素)。

问题:

如何获得 QComboBox 的实际宽度?

如何根据 QComboBox 的宽度裁剪文本?

您正在构造函数中调用 ui->qcombobox->width()。在此步骤中尚未计算组合框的大小。您需要等到第一个 showEvent 出现。尝试这样的事情:

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

为了在创建小部件时填充组合框,您需要执行以下操作:

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