c++ - qt creator 如何从主窗口获取布局?

标签 c++ qt c++14

我正在尝试在按下按钮时将 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();
}

ma​​inwindow.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);

结果:

enter image description here

关于c++ - qt creator 如何从主窗口获取布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40106101/

相关文章:

c++ - std::unique_lock<std::mutex> 还是 std::lock_guard<std::mutex>?

c++ - MATLAB:来自不同类的 OOP 调用函数

c++ - QtCore 是否也适合服务器端使用 'heavy' ?

c++ - 如何从 lambda-functor 的主体中增加一个变量?

c++ - 为什么 unique_ptr 有两个函数 reset 和 operator= 做类似的事情但不重载?

c++ - 接受指向 const 和非常量函数的指针的 typedef 模板

c++ - 真值表输入生成

c++ - 如何在C++中将字符串集合存储为键并将json存储为值

c++ - 如何在 Mac OS 的命令行中编译 Qt 代码

c++ - Qt Designer - 窗口不会比带像素图的 QLabel 小