QComboBox文字居中与指定位置弹出

6 篇文章 0 订阅
4 篇文章 0 订阅

头文件

#include <QStyledItemDelegate>
#include <QLineEdit>
#include <QComboBox>
#include <QMouseEvent>
class ComboBoxDelegate : public QStyledItemDelegate
{
public:
    ComboBoxDelegate(QObject * parent = 0);
    void paint(QPainter * painter, const QStyleOptionViewItem & option,
        const QModelIndex & index) const;
};

class PopupLineEdit : public QLineEdit
{
    Q_OBJECT

public:
    explicit PopupLineEdit(QWidget* parent = 0);
    explicit PopupLineEdit(const QString &str, QWidget* parent = 0);
   ~PopupLineEdit();
   Q_SIGNAL void clicked();
protected:
    void mouseReleaseEvent(QMouseEvent *);
    void mouseDoubleClickEvent(QMouseEvent *);

};

class CenterComboBox : public QComboBox
{
    Q_OBJECT

public:
    explicit CenterComboBox(QWidget *parent = 0);
    ~CenterComboBox();
    Q_SLOT void popupTop();
};

代码实现

#include "CenterComboBox.h"
#include <QListView>
#include <QVBoxLayout>
#include <QMouseEvent>
#include <QPoint>
#include <QPainter>

ComboBoxDelegate::ComboBoxDelegate(QObject * parent)
    : QStyledItemDelegate(parent)
{

}

void ComboBoxDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
{
    QString  str = index.data().toString();
    QStyleOptionViewItem myOption = option;
    myOption.displayAlignment = Qt::AlignCenter;
    QStyledItemDelegate::paint(painter, myOption, index);
}


PopupLineEdit::PopupLineEdit(QWidget* parent) : QLineEdit(parent)
{
}

PopupLineEdit::PopupLineEdit(const QString &str, QWidget* parent)
 : QLineEdit(parent)
{

}

PopupLineEdit::~PopupLineEdit()
{

}

void PopupLineEdit::mouseReleaseEvent(QMouseEvent *)
{
    emit clicked();
}

void PopupLineEdit::mouseDoubleClickEvent(QMouseEvent *)
{

}

CenterComboBox::CenterComboBox(QWidget *parent)
    : QComboBox(parent)
{
    PopupLineEdit* lineEdit = new PopupLineEdit(this);
    lineEdit->setReadOnly(true);
    lineEdit->setAlignment(Qt::AlignCenter);
    setLineEdit(lineEdit);
    connect(lineEdit, SIGNAL(clicked()), this, SLOT(popupTop()));
    ComboBoxDelegate *delegate = new ComboBoxDelegate(this);
    setItemDelegate(delegate);
    setMaxVisibleItems(20);
}

CenterComboBox::~CenterComboBox()
{
}


void CenterComboBox::popupTop()
{
    if (count() <= 1)
        return;
    showPopup();
    QWidget *popup = this->findChild<QFrame*>();
    //将当前坐标转换为显示器坐标
    QPoint pos = mapToGlobal(QPoint(0,0));
    popup->move(popup->x(), pos.y() - popup->height());
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值