需求
点击QComboBox时,下拉列表以多行多列的表格展示出来。
实现
直接上代码:
#include <QComboBox> #include <QTableWidget> #include <QVBoxLayout> #include <QWidget> #include <QEvent> #include <QMouseEvent> #include <QLineEdit> class ComboBoxWithTableWidget : public QComboBox { Q_OBJECT public: ComboBoxWithTableWidget(QWidget *parent = nullptr) : QComboBox(parent) { // 隐藏默认的下拉箭头 setEditable(true); lineEdit()->setReadOnly(true); // 创建一个隐藏的容器来存放我们的表格 popupWidget = new QWidget(this); popupWidget->setWindowFlags(Qt::Popup | Qt::FramelessWindowHint); QVBoxLayout *layout = new QVBoxLayout(popupWidget); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); tableWidget = new QTableWidget(5, 2, popupWidget); // 5行2列 for (int row = 0; row < 5; ++row) { for (int col = 0; col < 2; ++col) { QTableWidgetItem *item = new QTableWidgetItem(QString("Item %1%2").arg(row).arg(col)); tableWidget->setItem(row, col, item); } } tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); tableWidget->setSelectionMode(QAbstractItemView::SingleSelection); layout->addWidget(tableWidget); popupWidget->resize(220,200); connect(tableWidget, &QTableWidget::cellClicked, this, &ComboBoxWithTableWidget::onCellClicked); popupWidget->hide(); } protected: void showPopup() override { if (popupWidget->isHidden()) { QComboBox::showPopup(); //popupWidget->resize(this->width(), tableWidget->height() + 2); //(可能需要调整) popupWidget->move(this->mapToGlobal(QPoint(0, this->height()))); popupWidget->show(); tableWidget->setFocus(); } } void hidePopup() override { if (popupWidget->isVisible()) { popupWidget->hide(); QComboBox::hidePopup(); } } private slots: void onCellClicked(int row, int column) { QString text = tableWidget->item(row, column)->text(); this->setCurrentText(text); hidePopup(); // 选择后隐藏下拉列表 } private: QWidget *popupWidget = nullptr; QTableWidget *tableWidget= nullptr; };
示例效果
到此这篇关于Qt重写QComboBox实现下拉展示多列数据的文章就介绍到这了,更多相关Qt QComboBox下拉展示多列数据内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
来源链接:https://www.jb51.net/program/331666ou2.htm
© 版权声明
本站所有资源来自于网络,仅供学习与参考,请勿用于商业用途,否则产生的一切后果将由您(转载者)自己承担!
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
THE END
暂无评论内容