Important: Please read the Qt Code of Conduct -

Can I increase the max width of QLineEdit when setting its alignment in a layout?

  • I was testing around with layouts after trying the "Using Layouts" tutorial. I aligned a QLineEdit to Qt::AlignRight in a QHboxLayout. I noticed the width shrunk to 100 pixels (I checked with std::cout) compared to when I didn't edit its alignment. I wanted to make it wider. After seeing QlineEdit inherits QWidget, and seeing that QWidget has setMaximumWidth(), I tried using that with 200 pixels, but it didn't work. Can I increase the maximum width of a QLineEdit even if I align it in a layout?

    #include <QtWidgets>
    #include <iostream>
    int main(int argc, char *argv[]) {
        QApplication app(argc, argv);
        QWidget window;
        window.resize(320, 340);;
        window.setToolTip("This is the Top-level widget");
        window.setWindowTitle(QApplication::translate("toplevel", "Top-level widget"));
        QLineEdit edit("Line Edit", &window);
        edit.setMaximumWidth(200); //didn't make 'edit' wider
        QHBoxLayout layout;
        layout.setAlignment(&edit, Qt::AlignRight);
        std::cout << edit.width();
        return app.exec();

  • Lifetime Qt Champion


    Maximum width is the maximum size the widget can get, not the one it will have. If you want to ensure the size it at least 200 you should call setMinimumWidth.

  • That makes sense. Thanks!

Log in to reply