我正在尝试在按下按钮时将 QTableView 动态添加到主窗口。
看起来小部件类有一个成员布局,我可以设置它。
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,所以当我运行它时, View 只是作为它自己的窗口短暂弹出。
我是 c++ 和 qt 的新手,所以我做的事情可能根本就错了。这是获取布局并附加它的正确方法吗?如果是这样,我的错误是什么?如果不是,我应该如何解决这个问题?
最佳答案
检查 CentralWiget function .首先,创建一个小部件并将其设置为您的中央小部件。现在,为您的中央小部件定义一个布局,例如:水平布局:
// 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);
结果:
关于c++ - qt creator 如何从主窗口获取布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40106101/