示例代码创建了一个名为ComboBoxWidget的自定义QWidget类,并在initUI方法中创建了一个垂直布局。然后将一个只读的QLineEdit和一个QPushButton添加到布局中。当按钮被点击时,会调用showMenu方法,该方法创建一个QMenu并添加选项。每个选项连接到自定义的onOptionSelected方法,该方法在选择一个选项时被调用,并将选项的文本设置到QLineEdit中
#pragma execution_character_set("utf-8")
#include <QApplication>
#include <QWidget>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QPushButton>
#include <QMenu>
#include <QAction>
class ComboBoxWidget : public QWidget
{
public:
ComboBoxWidget(QWidget* parent = nullptr) : QWidget(parent)
{
initUI();
}
private:
void initUI()
{
QHBoxLayout* layout = new QHBoxLayout(this);
layout->setSpacing(0);
lineEdit = new QLineEdit(this);
lineEdit->setReadOnly(true);
lineEdit->setAlignment(Qt::AlignCenter);
button = new QPushButton("▼", this);
button->setFixedWidth(30);
layout->addWidget(lineEdit);
layout->addWidget(button);
connect(button, &QPushButton::clicked, this, &ComboBoxWidget::showMenu);
setLayout(layout);
setGeometry(300, 300, 200, 100);
setWindowTitle("ComboBox Example");
show();
}
void showMenu()
{
QMenu* menu = new QMenu(this);
menu->setFixedWidth(lineEdit->width() + button->width());
QAction* action1 = new QAction("Option 1", this);
connect(action1, &QAction::triggered, [this, action1]() { onOptionSelected(action1->text()); });
QAction* action2 = new QAction("Option 2", this);
connect(action2, &QAction::triggered, [this, action2]() { onOptionSelected(action2->text()); });
QAction* action3 = new QAction("Option 3", this);
connect(action3, &QAction::triggered, [this, action3]() { onOptionSelected(action3->text()); });
QAction* action4 = new QAction("Option 4", this);
connect(action4, &QAction::triggered, [this, action4]() { onOptionSelected(action4->text()); });
menu->addAction(action1);
menu->addAction(action2);
menu->addAction(action3);
menu->addAction(action4);
menu->exec(lineEdit->mapToGlobal(lineEdit->rect().bottomLeft()));
}
void onOptionSelected(const QString& text)
{
lineEdit->setText(text);
}
private:
QLineEdit* lineEdit;
QPushButton* button;
};
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
ComboBoxWidget widget;
widget.show();
return app.exec();
}
效果展示: