【问题标题】:QComboBox with click to lineEditQComboBox 与点击线编辑
【发布时间】: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 时,它会显示弹出窗口,但释放鼠标按钮后它消失了。

【问题讨论】:

  • QComboBox hides the pop-up on mouse release 在某些情况下。这可能会干扰您的实施。
  • 我通过以下步骤解决了问题:1.在ComboBox类中添加布尔属性preventHidePopup,2.在ComboBox类中重新实现hidePopup()方法来检查这个属性,如果这个属性调用QComboBox::showPopup() value 为 false,最后将此属性设置为 false。 3. 在构造函数中将该属性初始化为flase。 4. 在 ComboBox::lineEditPressed() 槽中调用 showPopup() 方法之前将该属性设置为 true。
  • 回答自己的问题并接受答案是完全没问题的。

标签: c++ qt


【解决方案1】:

请修改事件处理程序的documentation。当你在这个函数中显示弹出菜单时,释放事件会仓促发生冲突。我无法预测您对showPopup() 的实现,但请不要在其中创建弹出菜单。您可以显示、隐藏、分配,但从不创建。

【讨论】:

  • 感谢您的回答,但这对我没有帮助。我没有重新实现 showPopup,而是使用了从 QComboBox 继承的方法。请告诉我如何解决它。编写具有这种特性的简单派生类。
  • 不,我不是说showPopup() 是一个重新实现的函数。我的意思是这是您的实现,但请注意您在其中所做的事情。如果还是看不懂,建议编辑帖子添加这个功能的实现。
  • 我没有实现 showPopup() 方法。 QComboBox 类有 showPopup() 方法。
  • 好像是Qt的问题,需要覆盖showPopup()。很抱歉,但我希望能帮上忙。
猜你喜欢
  • 2016-06-26
  • 2015-07-16
  • 2017-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-07
  • 2011-07-23
  • 1970-01-01
相关资源
最近更新 更多