如何正确管理QToolButton的文本与图标?现有代码问题求助
Let's break down how to solve both of your problems with the QToolButton:
1. Move Text to the Left of the Icon
The Qt::ToolButtonTextBesideIcon style defaults to placing text on the right side of the icon. To swap their positions, you just need to use the Qt::ToolButtonTextBeforeIcon enum instead. This explicitly tells Qt to render the text before (to the left of) the icon.
2. Fix Window Resizing Adaptation
Your size policy setup is on the right track (QSizePolicy::Expanding for horizontal), but the button won't adapt properly unless it's embedded in a Qt layout manager (like QHBoxLayout, QVBoxLayout, etc.). Manual positioning (e.g., setGeometry) will break the resizing behavior.
Here's the updated code with both fixes, plus a layout example to ensure resizing works:
// Create the button as before QToolButton* nextPageBtn = new QToolButton(); nextPageBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); // Swap text and icon position nextPageBtn->setToolButtonStyle(Qt::ToolButtonTextBeforeIcon); nextPageBtn->setIcon(QIcon(":/next.png")); nextPageBtn->setText("Next"); // Add the button to a layout (critical for resizing) QHBoxLayout* layout = new QHBoxLayout(this); // 'this' is your parent widget layout->addWidget(nextPageBtn); // Optional: Add stretch factors if you want other widgets to share space // layout->addStretch(1);
Quick Notes:
- If your button is already in a layout, double-check that the layout is set as the parent widget's main layout (via
setLayout(layout)). - The
QSizePolicy::Expandingflag tells the button to take as much horizontal space as the layout allows when the window is resized, whileFixedkeeps its vertical height constant—this matches your original intent.
内容的提问来源于stack exchange,提问作者Theodore Tang

