【问题标题】:How to add Qbutton to the page without designing?如何在不设计的情况下将按钮添加到页面?
【发布时间】:2013-04-18 02:00:42
【问题描述】:

我是 QT 的新手。我开发了一个需要1024 line 的程序,每行有两个按钮、两个单选按钮和两个标签。我有两种方法。

  1. 在设计器模式下,我拖放 2*1204 按钮、2*1024 标签和 2*1024 单选按钮,这是不合逻辑的。
  2. 有一种方法可以在没有设计器模式和拖放的情况下添加此小部件 到页面,例如在运行时我单击一个按钮并在代码隐藏中 将此小部件(标签、按钮、单选按钮)添加到页面或类似的东西。

我在网络编程中做了第二种方式。这在QT中可能吗?或者类似的东西?

【问题讨论】:

    标签: c++ qt qt5


    【解决方案1】:

    您可以通过编程方式创建小部件并通过布局调整它们的位置。 例如,它可能看起来像这样:

    QVBoxLayout *topLayout = new QVBoxLayout();
    
    for (int lineNumber = 0; lineNumber < 1024; ++lineNumber)
    {
        QWidget *oneLineWidget = new QWidget(this);
        QHBoxLayout *oneLineWidgetLayout = new QHBoxLayout();
        { //added these brackets just for the ease of reading.
            QLabel *labFirst = new QLabel(tr("first label"), oneLineWidget);
            QLabel *labSecond = new QLabel(tr("second label"), oneLineWidget);
            QPushButton *bFirst = new QPushButton(tr("first button"), oneLineWidget);
            QPushButton *bSecond = new QPushButton(tr("second button"), oneLineWidget);
            QRadioButton *rbFirst = new QRadioButton(tr("first radiobutton"), oneLineWidget);
            QRadioButton *rbSecond = new QRadioButton(tr("second radiobutton"), oneLineWidget);
    
            oneLineWidgetLayout->addWidget(labFirst);
            oneLineWidgetLayout->addWidget(labSecond);
            oneLineWidgetLayout->addWidget(bFirst);
            oneLineWidgetLayout->addWidget(bSecond);
    
            //lets put one radioButton under another. 
            QVBoxLayout *radioButtonsLayout = new QVBoxLayout();
            {
                radioButtonsLayout->addWidget(rbFirst);
                radioButtonsLayout->addWidget(rbSecond);
            }
            //and now we can combine layouts.
            oneLineWidgetLayout->addLayout(radioButtonsLayout);
    
        }
        oneLineWidget->setLayout(oneLineWidgetLayout);
    
        topLayout->addWidget(oneLineWidget);
    }
    
    this->setLayout(topLayout);
    

    您可以使用不同类型的布局(QBoxLayout、QGridLayout、QFormLayout 等)。你可以从QLayout documentation开始。有一个继承它的类列表。 我希望它会有所帮助! :) 祝你好运!

    【讨论】:

    • P.S.我把它写在记事本上,并没有“在现实生活中”进行测试。所以它可能包含一些错误。但至少我希望它能为你指明正确的方向。
    【解决方案2】:

    您在 Qt Designer 中所做的一切最终都会转换为创建对象并将它们相互链接的 C++ 代码。

    因此,获取该代码(查看生成的头文件)并将其放入 for 循环是非常简单的。或者甚至自己重新开始,创建三个按钮并将它们添加到布局中只是几行代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 2018-04-15
      • 2022-11-14
      • 1970-01-01
      • 1970-01-01
      • 2016-10-11
      • 1970-01-01
      相关资源
      最近更新 更多