我想使用QSplitter來分割兩側的MainWindow。在左邊,我想要一個包含文件夾視圖的佈局,在右邊的另一個佈局中我將繪製一些內容。但我只能在QSplitter上添加小工具,而佈局不是小工具。 我發現的唯一類似的問題是這些:PyQt - 添加布局到QSplitter
http://www.qtcentre.org/threads/16856-QSplitter-multiple-layouts-how https://forum.qt.io/topic/8197/solved-qsplitter-and-qvboxlayout-problem
因此,根據上述鏈接,我的計劃是創建兩個佈局,然後將它們添加兩個QWidgets(使用setLayout的),然後將這些QWidgets添加到QSplitter(使用addWidget)。 我試圖將其應用於我的代碼,但不幸的是,當我將佈局添加到小部件時,什麼也沒有顯示出來!
是否有另一種方法來實現我想要的? 我誤解了答案嗎?
這是代碼。爲了讓代碼更簡單,我僅向您發送文件夾視圖佈局。 另外,我對pyqt和麪向對象編程完全陌生,因此歡迎任何有關如何改進它的建議!
在此先感謝!
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class Window(QMainWindow):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.UI()
def UI(self):
self.central_widget = QStackedWidget()
self.setCentralWidget(self.central_widget)
self.statusBar().showMessage("Ready")
page1 = FirstWidget(self)
page1.visualize_btn.clicked.connect(self.P_2)
self.central_widget.addWidget(page1)
self.setGeometry(10, 10, 800, 500) #All three methods have been inherited from the QWidget class.
self.showMaximized()
self.setWindowTitle('PTV')
self.setWindowIcon(QIcon('tuc_logo.png'))
def P_2(self):
page2 = VisualizeWidget(self)
self.central_widget.addWidget(page2)
self.central_widget.setCurrentWidget(page2)
class FirstWidget(QWidget):
def __init__(self, parent=None):
super(FirstWidget, self).__init__(parent)
self.buttons()
def buttons(self):
self.btn2 = QPushButton("Visualize")
self.buttonsLayout = QVBoxLayout()
self.buttonsLayout.addWidget(self.btn2)
self.visualize_btn = self.btn2
self.setLayout(self.buttonsLayout)
class VisualizeWidget(QWidget):
def __init__(self, parent=None):
super(VisualizeWidget, self).__init__(parent)
self.dirmodel = QFileSystemModel()
self.dirmodel.setFilter(QDir.NoDotAndDotDot | QDir.AllDirs) # Don't show files, just folders
self.folder_view = QTreeView(parent=self);
self.folder_view.setModel(self.dirmodel)
self.folder_view.clicked[QModelIndex].connect(self.clicked)
self.now_layout = QVBoxLayout()
self.now_layout.addWidget(self.folder_view)
#self.setLayout(self.now_layout)
#HERE is where I'm trying to add the layout to the widget.
self.left_widget = QWidget()
self.left_widget.setLayout(self.now_layout)
def set_path(self):
self.dirmodel.setRootPath("")
def clicked(self, index):
index = self.selectionModel.currentIndex()
dir_path = self.dirmodel.filePath(index)
self.filemodel.setRootPath(dir_path)
self.file_view.setRootIndex(self.filemodel.index(dir_path))
def main():
app = QApplication(sys.argv)
win = Window()
win.show()
app.exec_()
if __name__ == '__main__':
sys.exit(main())