Qt重寫QComboBox實(shí)現(xiàn)下拉展示多列數(shù)據(jù)
更新時(shí)間:2024年11月30日 11:35:17 作者:Lydro
這篇文章主要為大家詳細(xì)介紹了Qt如何重寫QComboBox實(shí)現(xiàn)下拉展示多列數(shù)據(jù),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
需求
點(diǎn)擊QComboBox時(shí),下拉列表以多行多列的表格展示出來。
實(shí)現(xiàn)
直接上代碼:
#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) { // 隱藏默認(rèn)的下拉箭頭 setEditable(true); lineEdit()->setReadOnly(true); // 創(chuàng)建一個(gè)隱藏的容器來存放我們的表格 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); //(可能需要調(diào)整) 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; };
示例效果
到此這篇關(guān)于Qt重寫QComboBox實(shí)現(xiàn)下拉展示多列數(shù)據(jù)的文章就介紹到這了,更多相關(guān)Qt QComboBox下拉展示多列數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++中內(nèi)存池和內(nèi)存分配區(qū)Arena概念詳解
在 C++ 中,內(nèi)存分配區(qū)(Arena)通常指的是預(yù)先分配的一大塊連續(xù)內(nèi)存空間,這種方法的主要目的是提高內(nèi)存分配和釋放的效率,下面就跟隨小編一起了解一下C++中內(nèi)存池和內(nèi)存分配區(qū)Arena相關(guān)概念吧2023-12-12C/C++ Socket設(shè)置接收超時(shí)時(shí)間的多種方法
網(wǎng)絡(luò)編程中經(jīng)常需要處理的一個(gè)問題就是如何正確地處理Socket超時(shí),對于C/C++,有幾種常用的技術(shù)可以用來設(shè)置Socket接收超時(shí)時(shí)間,在這篇文章中,我們將詳細(xì)介紹如何在C/C++中設(shè)置Socket的非阻塞模式以及如何配置接收超時(shí)時(shí)間,需要的朋友可以參考下2024-01-01