每次我在QMainWindow的mainToolBar中动态添加一个按钮时,QDockWidget都会将其大小调整为原始大小。
我的问题:
这说明了我的困境。 这是启动时的示例应用程序:
现在,我手动调整QDockWindow的大小。
现在,我按下“ F1”,这将在QMainWindow的mainToolBar上创建一个工具按钮,并且QDockWindow会自动调整为原始大小。
这是这个简单应用程序的代码:
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QKeyEvent>
#include <QInputDialog>
#include <QToolButton>
#include <QPlainTextEdit>
#include <QDockWidget>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
QToolButton *Create_toolbutton(QString);
protected:
void keyPressEvent(QKeyEvent*);
};
#endif // MAINWINDOW_H
mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->setCentralWidget(new QPlainTextEdit());
this->addDockWidget(Qt::RightDockWidgetArea, new QDockWidget());
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::keyPressEvent(QKeyEvent * ke)
{
if(ke->key() == Qt::Key_F1){
ui->mainToolBar->addWidget(Create_toolbutton("new button"));
}
QMainWindow::keyPressEvent(ke);
}
QToolButton * MainWindow::Create_toolbutton(QString toolbutton_name)
{
QToolButton * new_qtoolbutton = new QToolButton();
new_qtoolbutton->setText(toolbutton_name);
new_qtoolbutton->setArrowType(Qt::ArrowType::RightArrow);
new_qtoolbutton->setToolButtonStyle(Qt::ToolButtonStyle::ToolButtonTextBesideIcon);
return new_qtoolbutton;
}
答案 0 :(得分:0)
我正在使用 resizeDocks ,它对我来说已经足够了。
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->setCentralWidget(new QPlainTextEdit());
auto * dock = new QDockWidget();
this->addDockWidget(Qt::RightDockWidgetArea, dock);
resizeDocks({dock}, {100}, Qt::Horizontal);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::keyPressEvent(QKeyEvent * ke)
{
if(ke->key() == Qt::Key_F1){
ui->mainToolBar->addWidget(Create_toolbutton("new button"));
}
QMainWindow::keyPressEvent(ke);
}
QToolButton * MainWindow::Create_toolbutton(QString toolbutton_name)
{
QToolButton * new_qtoolbutton = new QToolButton();
new_qtoolbutton->setText(toolbutton_name);
new_qtoolbutton->setArrowType(Qt::ArrowType::RightArrow);
new_qtoolbutton->setToolButtonStyle(Qt::ToolButtonStyle::ToolButtonTextBesideIcon);
return new_qtoolbutton;
}