current index

海前 王 - Sep 2 - - Dev Community

#include <QApplication>
#include <QComboBox>
#include <QMainWindow>
#include <QVBoxLayout>
#include <QPushButton>
#include <QMessageBox>

class MainWindow : public QMainWindow {
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);

private slots:
    void showCurrentIndex();

private:
    QComboBox *comboBox;
};

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
    QWidget *centralWidget = new QWidget(this);
    QVBoxLayout *layout = new QVBoxLayout(centralWidget);

    comboBox = new QComboBox(this);
    comboBox->addItem("Item 1");
    comboBox->addItem("Item 2");
    comboBox->addItem("Item 3");

    QPushButton *button = new QPushButton("Show Current Index", this);
    connect(button, &QPushButton::clicked, this, &MainWindow::showCurrentIndex);

    layout->addWidget(comboBox);
    layout->addWidget(button);

    setCentralWidget(centralWidget);
}

void MainWindow::showCurrentIndex() {
    int index = comboBox->currentIndex();
    QString itemText = comboBox->currentText();
    QMessageBox::information(this, "Current Index", QString("Current Index: %1\nCurrent Item: %2").arg(index).arg(itemText));
}

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

    MainWindow window;
    window.show();

    return app.exec();
}

#include "main.moc"
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .