![](/img/trans.png)
[英]How would I open a new window from a button in the main window using Qt Creator?
[英]qt creator how to get layout from main window?
我試圖在按下按鈕時將QTableViews動態添加到主窗口。
看起來小部件類具有成員布局,我可以對其進行設置。
qwidget.h:
public:
QLayout *layout() const;
void setLayout(QLayout *);
主要:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGridLayout *layout = new QGridLayout();
MainWindow w;
w.setLayout( layout );
w.show();
return a.exec();
}
mainwindow.cpp的一部分:
void MainWindow::on_btn_main_run_clicked()
{
this->Run();
}
void MainWindow::Run() {
this->up_dr_ = std::make_unique<DataReader>(
DataReader( "C:/CPP/Simulator/log_file.txt" )
);
up_dr_->ReadFile();
up_dr_->PrintLines();
TableModel model( this );
QTableView table_view;
table_view.setModel( &model );
// this line below there does not work. It throws the error left of add widget must point to class/...
this->layout->addWidget( &table_view );
table_view.show();
}
我無法從主窗口獲取布局成員來附加qtableview,因此在運行它時,視圖只是短暫地彈出作為其自己的窗口。
我是c ++和qt的新手,所以可能我在做某些根本上錯誤的事情。 這是獲取布局並將其附加的正確方法嗎?如果是,我在這里的錯誤是什么? 如果沒有,我該如何解決?
檢查CentralWiget功能 。 首先,創建一個小部件並將其設置為您的中央小部件。 現在,為中央小部件定義一個布局,例如:水平布局:
// Add a layour to your central widget
QHBoxLayout* layout = new QHBoxLayout;
this->centralWidget()->setLayout(layout);
當您想將小部件隱藏/添加到中央小部件時,只需使用:
// Now, we could add an element to the widget
QHBoxLayout* layout = this->centralWidget()->layout();
QTableView* view = new QTableView;
view->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding,);
layout->addWidget(view);
例:
QWidget* main = new QWidget(this);
main->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
this->setCentralWidget(main);
QHBoxLayout* layout = new QHBoxLayout(this);
this->centralWidget()->setLayout(layout);
QTableWidget* table = new QTableWidget(this);
table->setColumnCount(2);
table->setRowCount(3);
table->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
this->centralWidget()->layout()->addWidget(table);
結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.