【发布时间】:2013-09-27 07:39:34
【问题描述】:
我创建了一个 GUI 宽度 Qt Creator (Qt 5.0.1),当然也使用了布局。出于美学原因,我希望 QPushButton 与放置在 GUI 其他角落的另一个 QPushButton 具有相同的宽度。当更改窗口大小时,此另一个按钮会动态更改大小,这是所需的行为。
有没有办法(动态地)链接这些按钮的大小而不改变布局?如果可能的话,我想避免固定尺寸。
【问题讨论】:
标签: c++ qt qpushbutton
我创建了一个 GUI 宽度 Qt Creator (Qt 5.0.1),当然也使用了布局。出于美学原因,我希望 QPushButton 与放置在 GUI 其他角落的另一个 QPushButton 具有相同的宽度。当更改窗口大小时,此另一个按钮会动态更改大小,这是所需的行为。
有没有办法(动态地)链接这些按钮的大小而不改变布局?如果可能的话,我想避免固定尺寸。
【问题讨论】:
标签: c++ qt qpushbutton
您可以覆盖第一个的resizeEvent并将信号(带大小)发送到第二个。
【讨论】:
我会提出以下解决方案(没有子分类按钮类)。实际上下面的代码可以用于同步任何小部件,不仅仅是QPushButtons。
SizeSynchronizer 类:
/// Synchronizes the given widget's size with other's - one that the SizeSynchronizer installed on.
class SizeSynchronizer : public QObject
{
public:
SizeSynchronizer(QWidget *w)
:
m_widget(w)
{}
bool eventFilter(QObject *obj, QEvent *ev)
{
if (m_widget) {
if (ev->type() == QEvent::Resize) {
QResizeEvent *resizeEvent = static_cast<QResizeEvent *>(ev);
m_widget->resize(resizeEvent->size());
}
}
return QObject::eventFilter(obj, ev);
}
private:
QWidget *m_widget;
};
类使用的简单演示——同步两个按钮:
int main(int argc, char *argv[])
{
[..]
// First button will be synchronized with the second one, i.e. when second
// resized, the first one will resize too.
QPushButton pb1("Button1");
QPushButton pb2("Button2");
// Create synchronizer and define the button that should be synchronized.
SizeSynchronizer sync(&pb1);
pb2.installEventFilter(&sync);
pb2.show();
pb1.show();
[..]
}
【讨论】: