I have a QListWidget
and a QPushButton
that clears the QListWidget
. Right now my button is next to the QListWidget
leaving awkward empty space.
I would like to place the button over the QListWidget
so that is would cover the right bottom corner.
I tried just placing the button like this
QPushButton* button = new QPushButton(ui->listwidget);
button->show();
And it does create a "floating" button over my widget, but I can't seem to find a way to place it correctly. Maybe I could by trials-and-errors find the right cooridantes, but the problem is that my main window is resizable so I don't want the button to end up in the middle of the list or complately outside of view.
Does someone have a better idea than this?
This should be possible, though I'm not sure you're going to like how much trouble it is or the final result. But in a nutshell...
Create the QPushButton
with your window as the parent (I'm assuming the QListWidget
is inside a window or some other container QWidget
which has the layout you mentioned). Whatever the parent widget is, that will be your frame of reference for the position coordinates of your button.
You will then need to position your button with QWidget::pos
. The trick is where and when.
Since the position is relative to the parent, you will need to get the parent's inner width and height with QWidget::size()
, subtract your button's width and height (QWidget::frameSize()
), and set the new position accordingly.
You will need to do this for each resize event of the parent widget. So, one way is to re-implement QWidget::resizeEvent()
in your parent window, and position the button from there.
This is not tested...
QPushButton* button = new QPushButton(this); // parent is current QWidget
button->show();
...
void MyWidget::resizeEvent(QResizeEvent *event) Q_DECL_OVERRIDE
{
QSize btnSize = button->frameSize();
QSize containerSize = this->size();
int newX = containerSize.width() - btnSize.width() - 10; // 10 is arbitrary margin
int newY = containerSize.height() - btnSize.height() - 10;
// position the button
button->move(newX, newY);
// call the superclass handler: substitute the actual superclass here
QWidget::resizeEvent(event);
}
You will most likely need to tweak things further, perhaps quite a bit, but that should be the general idea. The key is to reposition the button on each resize of the parent, which includes when it is initially shown.
HTH