簡體   English   中英

Qt C ++ GUI QSpinBox是否存儲輸入?

[英]Qt C++ GUI QSpinBox Storing Input?

我將如何從旋轉框中獲取用戶輸入並將其用作值? 換句話說,如果我想將QSpinBox的輸入存儲到變量中,我將如何去做。 我在Qt GUI上真的很新,所以任何輸入都將不勝感激。

為了對Qt中的GUI元素做出反應,您可以連接到這些元素發出的信號。 同樣,如果您有指向其實例的指針,則可以查詢和更改其狀態和屬性。

這是您正在尋找的簡單示例

#include <QApplication>
#include <QVBoxLayout>
#include <QLabel>
#include <QSpinBox>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    // The widget, contains a layout
    QWidget * w;
    w = new QWidget;

    // The layout arranges and holds
    // all the children of the widget
    QVBoxLayout * vbox;

    vbox = new QVBoxLayout;

    // The user input element, the spinbox!
    QSpinBox * spinbox;

    spinbox = new QSpinBox();
    spinbox->setValue(5);// example of using a pointer to edit its states

    // now add it to the layout
    vbox->addWidget(spinbox);

    // add in an element to connect to,
    // the infamous QLabel
    QLabel * label;

    label = new QLabel("spinbox output");

    // add it also to the layout
    vbox->addWidget(label);

    // connection can happen anytime as long as the two elements
    // are not null!

    // This connection takes advantage of signals and slots
    // and making their connection at runtime.

    // if a connect call fails you should be able to see why in the
    // application output.
    QObject::connect(spinbox, SIGNAL(valueChanged(QString)),
        label, SLOT(setText(QString)));

    // associate the layout to the widget
    w->setLayout(vbox);

    // make the widget appear!
    w->show();

    return a.exec();
}

我通常將大多數GUI元素的初始化和連接放入主QWidgetQMainWindow的構造函數或方法中。 我經常從GUI輸入元素(如Spinbox)中獲取信號,並將其連接到子類QWidget上定義的自定義插槽。 然后,如果我想用不同的輸入值顯示它或將輸出增加2,我可以輕松地做到這一點。

// in the constructor of my Widget class
// after spinbox has been initialized
QObject(m_spinbox, SIGNAL(valueChanged(int)),
    this, SLOT(on_spinboxValueChanged(int)));

void Widget::on_spinboxValueChanged(int i)
{
    // here m_label is a member variable of the Widget class
    m_label->setText(QString::number(i + 2)); 

    // if accessing the value in this function is inconvenient, you can always 
    // use a member variable pointer to it to get its stored value.
    // for example:
    int j = m_spinbox->value();
    qDebug() << "Spinbox value" << j;
}

相同的事情可以在QML和Qt Quick中完成,並且對於許多人來說,由於它與javascript和css的距離如此之近,因此更加容易和直觀。

Qt Creator還具有用於生成表單的工具,它提供了另一種方法來創建具有布局的小部件,然后在訪問元素時通過ui變量進行操作。

Qt的文檔和示例也很棒。 花時間學習和閱讀它們是值得的。

希望能有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM