qt点击按钮弹出下拉窗口(不用Qmenu)
时间: 2023-07-12 07:34:27 浏览: 56
如果您不想使用QMenu,可以使用QWidget或QFrame类来创建下拉窗口。以下是一个示例:
```python
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QHBoxLayout, QFrame, QLabel, QWidget
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
button = QPushButton("Click me", self)
button.setFixedWidth(100)
button.setFixedHeight(30)
button.move(50, 50)
button.clicked.connect(self.show_menu)
self.dropdown = Dropdown(self)
main_layout = QVBoxLayout()
main_layout.addWidget(button)
main_layout.addWidget(self.dropdown)
central_widget = QWidget()
central_widget.setLayout(main_layout)
self.setCentralWidget(central_widget)
self.show()
def show_menu(self):
if not self.dropdown.isVisible():
button = self.sender()
self.dropdown.move(button.mapToGlobal(button.rect().bottomLeft()))
self.dropdown.show()
else:
self.dropdown.hide()
class Dropdown(QFrame):
def __init__(self, parent=None):
super().__init__(parent)
self.setFixedWidth(200)
self.hide()
label1 = QLabel("Option 1", self)
label2 = QLabel("Option 2", self)
layout = QHBoxLayout()
layout.addWidget(label1)
layout.addWidget(label2)
self.setLayout(layout)
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
app.exec_()
```
在这个示例中,我们创建了一个QPushButton和一个自定义QWidget作为下拉窗口。当QPushButton被点击时,我们调用show_menu函数来显示或隐藏下拉窗口。在show_menu函数中,我们检查下拉窗口的可见性,如果下拉窗口当前不可见,我们将其移动到QPushButton的下方左侧,并显示它。否则,我们将其隐藏。
在Dropdown类中,我们添加了两个QLabel以演示自定义操作。我们使用QHBoxLayout来布局这些QLabel,并将其设置为QWidget的布局。