【发布时间】:2020-05-06 11:01:21
【问题描述】:
我希望 QComboBox 的派生类具有以下附加功能:
当用户点击该组合框的QLiineEdit时,效果必须与点击组合框右侧的箭头相同(showPopup()方法)。
我的尝试是:
文件 lineedit.h
#ifndef LINEEDIT_H
#define LINEEDIT_H
#include <QLineEdit>
class LineEdit : public QLineEdit {
Q_OBJECT
public:
LineEdit(QWidget *parent = nullptr);
signals:
void pressed();
protected:
void mousePressEvent(QMouseEvent *event) override;
};
#endif // LINEEDIT_H
文件 lineedit.cpp
#include "lineedit.h"
#include <QMouseEvent>
LineEdit::LineEdit(QWidget *parent) : QLineEdit(parent) {}
void LineEdit::mousePressEvent(QMouseEvent *event) {
QLineEdit::mousePressEvent(event);
emit pressed();
event->accept();
}
文件combobox.h
#ifndef COMBOBOX_H
#define COMBOBOX_H
#include <QComboBox>
class ComboBox : public QComboBox {
Q_OBJECT
public:
ComboBox(QWidget *parent = nullptr);
private slots:
void lineEditPressed();
};
#endif // COMBOBOX_H
文件combobox.cpp
#include "combobox.h"
#include "lineedit.h"
ComboBox::ComboBox(QWidget *parent) : QComboBox(parent) {
setLineEdit(new LineEdit);
connect(lineEdit(), SIGNAL(pressed()), this, SLOT(lineEditPressed()));
}
void ComboBox::lineEditPressed() { showPopup(); }
但是,当我按下 lineEdit 时,它会显示弹出窗口,但释放鼠标按钮后它消失了。
【问题讨论】:
-
QComboBoxhides the pop-up on mouse release 在某些情况下。这可能会干扰您的实施。 -
我通过以下步骤解决了问题:1.在ComboBox类中添加布尔属性preventHidePopup,2.在ComboBox类中重新实现hidePopup()方法来检查这个属性,如果这个属性调用QComboBox::showPopup() value 为 false,最后将此属性设置为 false。 3. 在构造函数中将该属性初始化为flase。 4. 在 ComboBox::lineEditPressed() 槽中调用 showPopup() 方法之前将该属性设置为 true。
-
回答自己的问题并接受答案是完全没问题的。