2017-08-29 86 views
1

我需要將我的自定義小部件放置在我的MainWindow中的指定位置。Qt將小部件放置在自定義位置

在屏幕上我標記了紅色的矩形「小部件」放置在我想放置我的小部件的地方。我想在QmenuBar和QToolBar之上放置小部件。

我試過setCentralWidget,但它在整個窗口上展開了小部件。

圖片展示我的問題,我的小部件的

代碼:

timers.cpp

#include "QtWidgets" 
#include "timers.h" 

static QLabel *createDragLabel(const QString &text, QWidget *parent) 
{ 
    QLabel *label = new QLabel(text, parent); 
    label->setAutoFillBackground(true); 
    label->setFrameShape(QFrame::Panel); 
    label->setFrameShadow(QFrame::Raised); 
    return label; 
} 

Timers::Timers(QWidget *parent) : QWidget(parent) 
{ 
    QLabel *wordLabel = createDragLabel("dupppa", this); 
} 

mainwindow.cpp

MainWindow::MainWindow() 
{ 

    initMenu(); 
    initButtons(); 

    TrackWindow *trackWindow = new TrackWindow(); 
    setCentralWidget(trackWindow); 

    Timers *firstTimer = new Timers(); 
    //setCentralWidget(firstTimer); // suck 

} 
+1

我不知道是否有可能有自由浮動小窗口重疊您的菜單。一般來說,只能在父窗口部件的邊界內設置位置,並通過父座標中的'QWidget :: move(int x,int y)'來設置它。因此,您無法將該小部件設置爲中央小部件,您需要將父級設置爲也是菜單和工具欄小部件的父級的「QWindow」。 – xander

回答

0

好的,這裏有一個解決方案:使MainWidget成爲您的小部件的父項,但不要將其添加到父級佈局。然後基本上移動你的小部件與QWidget::move()和設置其大小QWidget::resize()。這樣你就可以獲得絕對位置的小部件。

的工作代碼的摘錄:

#include <QLayout> 

MainWindow::MainWindow(QWidget *parent) : 
    QMainWindow{ parent }, 
    ui{ new Ui::MainWindow } 
{ 
    ui->setupUi(this); 

    menuBar = new QMenuBar { this }; 
    toolBar = new QToolBar { this }; 
    textEdit = new QTextEdit { this }; 

    menuBar->addMenu("File"); 
    menuBar->addMenu("Edit"); 
    menuBar->addMenu("About"); 

    toolBar->addAction("Copy"); 
    toolBar->addAction("Cut"); 
    toolBar->addAction("Insert"); 
    toolBar->addAction("Other tools"); 

    layout()->setMenuBar(menuBar); 
    addToolBar(toolBar); 

    textEdit->setText("Your widget"); 
    textEdit->resize(90, 30); 
    textEdit->move(250, 10); 
} 

截圖: enter image description here

+0

這是一個很好的解決方案,但我試圖將其實施到我的程序中,但我無法完成工作。我是Qt的新手,必須學習如何爲菜單,工具欄和其他小部件創建MainWindow父級。我仍會嘗試,直到完成。謝謝你的答案。 –

+0

對於任何'QObject',您都可以指定另一個'QObject'作爲其父對象。當你說'新的QMenuBar {this}'時,你指定'this'作爲新創建的'QMenuBar'的父節點。在我們的例子中'this'指的是'MainWindow'。現在'MainWindow'是'QMenuBar'的父親:) – WindyFields

+0

我甚至不是一個Qt專家,但我基本上想表明,如果你只是創建一個小部件,比如'textEdit',並將你的'MainWindow'設置爲它的父'QTextEdit {this}',那麼你可以像使用'textEdit-> move(250,10)'一樣使用'QWidget :: move(int x,int y)'來自由移動它。 – WindyFields

相關問題